截至目前,我的数据在一个巨大的列表中,每三行数据包含同一观察的信息。这意味着当我操纵数据框时,它们需要作为一个组在一起。这是我面临的问题,我想将数据从行转换为列,但我只需要三列(即,每种信息类型为一列)。
为了说明这一点,现在是我的数据框:
1
00:09:49.350 --> 00:09:49.800
Hello, good.
2
00:09:54.750 --> 00:09:55.350
Customer: Morning.
3
00:09:56.100 --> 00:09:56.670
Morning.
这就是我希望的:
1 00:09:49.350 --> 00:09:49.800 Hello, good.
2 00:09:54.750 --> 00:09:55.350 Customer: Morning.
3 00:09:56.100 --> 00:09:56.670 Morning.
感谢您的时间!
利用 cbind
#sample data
df <- structure(list(X1 = c("1", "00:09:49.350 --> 00:09:49.800", "Hello, good.",
"2", "00:09:54.750 --> 00:09:55.350", "Customer: Morning.", "3",
"00:09:56.100 --> 00:09:56.670", "Morning.")), class = "data.frame", row.names = c(NA,
-9L))
现在这样进行
n1 <- nrow(df)
as.data.frame(cbind(df[1:n1 %% 3 == 1,], df[1:n1 %% 3 == 2,], df[1:n1 %% 3 == 0,]))
V1 V2 V3
1 1 00:09:49.350 --> 00:09:49.800 Hello, good.
2 2 00:09:54.750 --> 00:09:55.350 Customer: Morning.
3 3 00:09:56.100 --> 00:09:56.670 Morning.
解释使用mod函数,即%%
在其中,R
我们可以轻松地从第一行,第二行和第三行分别分组选择第三行,最后将cbind
它们全部组合在一起。as.data.frame()
将根据需要将结果放入data.frame,这是可选的。
此后,您可以轻松操作列类型
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句