大家好:我正在使用 tibbles 来总结我的数据,现在遇到了问题。我需要将 tibble 中的数据以 Excel 或 csv 文件格式发送给合作伙伴。问题是它要求 csv(或 excel)文件处于特定的排列(没有整洁的数据),所以我想知道你是否可以帮助我一点,至少将我的 tibble 放入 csv 文件中这样就可以很容易地在 Excel 中对其进行编辑。
小标题看起来像这样:
# A tibble: 1,024 x 4
# Groups: Treatment [16]
Treatment Pressure mean std
<chr> <dbl> <dbl> <dbl>
1 "I Control " 0. 97.2 1.03
2 "I Control " 0.689 94.1 1.35
3 "I Control " 1.38 90.9 2.01
4 "I Control " 2.07 89.5 2.20
5 "I Control " 2.76 88.8 2.45
6 "I Control " 3.45 87.6 2.88
7 "I Control " 4.14 86.9 3.22
8 "I Control " 4.83 83.9 5.53
9 "I Control " 5.52 83.1 5.55
10 "I Control " 6.21 81.9 6.24
变量“Treatment”有 16 个不同的值。我想要一个如下所示的 csv 文件:
从图中可以看出,变量“Treatment”中的每个值都有 2 行,一行包含变量“mean”的值,另一行包含变量“std”的值。在 csv 表中,每一列代表变量“压力”的每个不同值。
有什么想法或建议吗?提前感谢您抽出时间。
最佳答案
这只是将数据从宽格式转换为长格式,然后再次转换为所需的宽格式的问题。有几种可能的解决方案,在本例中,我使用 tidyr 包中的 gather
和 spread
。
df<-structure(list(Treatment = structure(c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L), .Label = "I Control ", class = "factor"), Pressure = c(0,
0.689, 1.38, 2.07, 2.76, 3.45, 4.14, 4.83, 5.52, 6.21), mean = c(97.2,
94.1, 90.9, 89.5, 88.8, 87.6, 86.9, 83.9, 83.1, 81.9), std = c(1.03,
1.35, 2.01, 2.2, 2.45, 2.88, 3.22, 5.53, 5.55, 6.24)), .Names = c("Treatment",
"Pressure", "mean", "std"), class = "data.frame", row.names = c(NA, -10L))
library(tidyr)
long<-gather(df, variable, value, 3:4)
answer<-spread(long, Pressure, value)
write.csv(answer, "Answer.csv")
当然,如果不同治疗的压力不同,最终的数据帧将非常困惑。
关于r - R中从tibble到txt或excel文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49946867/