提问人:george1994 提问时间:4/29/2022 最后编辑:AndrewGBgeorge1994 更新时间:4/29/2022 访问量:515
如何在 R 中将数据帧的一列拆分为新列?
How to split up a column of a dataframe into new columns in R?
问:
我有一个包含一列和 n 行的数据帧,如下所示:
data.frame(rep(x=c("c","a","c","b","c","d"),times=c(1,4,1,4,1,4)))
现在,我想拆分数据帧的这一列,每创建一个新列。目的是将只有一列的数据帧转换为以下形式:c
c | c | c |
---|---|---|
一个 | b | d |
一个 | b | d |
一个 | b | d |
一个 | b | d |
答:
2赞
AndrewGB
4/29/2022
#1
使用 ,我们可以在每次列中出现时创建一个新组,然后我们可以透视数据。通常,不鼓励使用重复的名称,因此我创建了一个连续的列名称。tidyverse
c
x
c
library(tidyverse)
results <- df %>%
group_by(idx = cumsum(x == "c")) %>%
filter(x != "c") %>%
mutate(rn = row_number()) %>%
pivot_wider(names_from = idx, values_from = x, names_prefix = "c_") %>%
select(-rn)
输出
c_1 c_2 c_3
<chr> <chr> <chr>
1 a b d
2 a b d
3 a b d
4 a b d
但是,如果您真的想要重复的名称,那么我们可以添加:set_names
purrr::set_names(results, "c")
c c c
<chr> <chr> <chr>
1 a b d
2 a b d
3 a b d
4 a b d
或者在基数 R 中,我们可以用 创建分组,然后拆分这些组,然后用 绑定回去。然后,我们删除包含字符的第一行。cumsum
cbind
c
names(df) <- "c"
do.call(cbind, split(df, cumsum(df$c == "c")))[-1,]
# c c c
#2 a b d
#3 a b d
#4 a b d
#5 a b d
0赞
Onyambu
4/29/2022
#2
您的列具有相同数量的值,如给定的示例中所示:
unstack(df, x ~ cumsum(x=="c"))
X1 X2 X3
1 c c c
2 a b d
3 a b d
4 a b d
5 a b d
然后,您可以删除第一行
评论