[英]From tibble to txt or excel file in R
大家好:我正在使用 tibbles 来总结我的数据,现在我遇到了一个问题。 我需要将我拥有的数据以 excel 或 csv 文件格式发送给合作伙伴。 问题是它要求 csv(或 excel)文件处于特定的排列(没有整洁的数据)所以我想知道你是否可以帮助我,至少,将我的 tibble 放入一个 csv 文件中在excel本身中很容易编辑它的方式。
tibble 看起来像这样:
# 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
我有 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")
当然,如果压力因治疗而异,最终的数据框将非常混乱。
你的数据不容易复制,也没有充分代表治疗的可变性,所以我做了一些随机数据:
set.seed(2)
dat <- data_frame(
Treatment = rep(letters[1:2], each=4),
Pressure = sample(100, size=8),
mean = sample(100, size=8),
std = sample(100, size=8)
)
library(dplyr)
library(tidyr)
这里有一个方法:
dat %>%
gather(k, v, -Treatment) %>%
group_by(Treatment, k) %>%
nest() %>%
mutate(data = map(data, ~ as.data.frame(t(.$v)))) %>%
unnest()
# # A tibble: 6 x 6
# Treatment k V1 V2 V3 V4
# <chr> <chr> <int> <int> <int> <int>
# 1 a Pressure 19 70 57 17
# 2 b Pressure 91 90 13 78
# 3 a mean 47 55 99 24
# 4 b mean 74 18 39 80
# 5 a std 98 23 44 8
# 6 b std 64 37 79 14
即使您的治疗不平衡,这也很有效:
dat <- dat[-8,]
dat %>%
gather(k, v, -Treatment) %>%
group_by(Treatment, k) %>%
nest() %>%
mutate(data = map(data, ~ as.data.frame(t(.$v)))) %>%
unnest()
# # A tibble: 6 x 6
# Treatment k V1 V2 V3 V4
# <chr> <chr> <int> <int> <int> <int>
# 1 a Pressure 19 70 57 17
# 2 b Pressure 91 90 13 NA
# 3 a mean 47 55 99 24
# 4 b mean 74 18 39 NA
# 5 a std 98 23 44 8
# 6 b std 64 37 79 NA
从这里开始,只需附加%>% write.csv(path, na="")
或%>% readr::write_csv(path, na="")
,这样空单元格就不会填充到 excel 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.