作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数据框如下:
days target probability
1 75 0.80 0.9060341
2 100 0.90 0.75
df <- structure(list(days = c(75, 100, 120, 150, 200, 300, 75, 100,
120, 150, 200, 300, 75, 100, 120, 150, 200, 300, 75, 100, 120,
150, 200, 300, 75, 100, 120, 150, 200, 300, 75, 100, 120, 150,
200, 300), target = c(0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.9, 0.9,
0.9, 0.9, 0.9, 0.9, 1, 1, 1, 1, 1, 1, 1.05, 1.05, 1.05, 1.05,
1.05, 1.05, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.2, 1.2, 1.2, 1.2,
1.2, 1.2), probability = c(0.90603410539241, 0.90603410539241,
0.90603410539241, 0.90603410539241, 0.90603410539241, 0.904213051602258,
0.733995206180212, 0.733995206180212, 0.733995206180212, 0.733995206180212,
0.733995206180212, 0.731795453278156, 0.512082243536284, 0.512082243536284,
0.512082243536284, 0.512082243536284, 0.512082243536284, 0.511492313399902,
0.390943562448882, 0.390943562448882, 0.390943562448882, 0.390943562448882,
0.390943562448882, 0.391451116324459, 0.282452594645645, 0.282452594645645,
0.282452594645645, 0.282452594645645, 0.282452594645645, 0.283766337160544,
0.106271449405461, 0.106271449405461, 0.106271449405461, 0.106271449405461,
0.106271449405461, 0.107778317673786)), .Names = c("days", "target",
"probability"), class = "data.frame", row.names = c(1L, 2L, 3L,
4L, 5L, 7L, 9L, 10L, 11L, 12L, 13L, 15L, 17L, 18L, 19L, 20L,
21L, 23L, 25L, 26L, 27L, 28L, 29L, 31L, 33L, 34L, 35L, 36L, 37L,
40L, 43L, 44L, 45L, 46L, 47L, 49L))
并且希望在具有以下标题的 CSV 文件中发送一行:
day75_target0.80、day100_target0.9 等等——每行中的值应该只是相应的概率。
想法?
最佳答案
通过简单地连接字段然后转置数据帧来考虑这种基本的 R 方法:
# CONCATENATING DAYS AND TARGETS FIELDS
newdf <- data.frame(daystarget = paste0("day", df$days, "_target", df$target,
probability = df$probability), stringsAsFactors=F)
# ROUND PROBABILITY TO ONE DIGIT
newdf$probability <- round(as.numeric(newdf$probability), 1)
# TRANSPOSE DATA FRAME
finaldf <- data.frame(t(newdf),stringsAsFactors=F)
# RENAME COLUMNS TO FIRST ROW
names(finaldf) <- finaldf[1,]
# REMOVE PREVIOUS FIRST ROW
finaldf <- finaldf[2,]
# RESET ROW NAMES
row.names(finaldf) <- 1:nrow(finaldf)
write.csv(finaldf, "FinalDF.csv", row.names=F)
# day75_target0.8 day100_target0.8 day120_target0.8 day150_target0.8 ...
#1 0.9 0.9 0.9 0.9 ...
关于R如何将数据框转换为单行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386193/
我是一名优秀的程序员,十分优秀!