首页 > 解决方案 > 计算数据框列中的元素,然后在 R 中创建单独的列

问题描述

我自己为解决方案苦苦挣扎了几天。希望你能帮忙。我已经检查了以下内容:

我有一个数据框如下:

df<-list(column=c("apple juice,guava-peach juice,melon apple juice","orange juice,pineapple strawberry lemon juice"))
df<-data.frame(df)

我想在自己的列中用“,”分隔每个元素。列数必须基于列中每行的最大元素

 column1               column2                              column3
 apple juice       guava-peach juice                  melon apple juice
 orange juice    pineapple strawberry lemon juice             NA

我尝试使用

library(tidyverse)
library(stringr)

#want to calculate number of columns needed and the sequence 

x<-str_count(df$column)

results<-df%>%separate(column,x,",")

不幸的是,我没有得到我想要的。感谢您的帮助。

标签: rcounttidyrtidyverse

解决方案


你是这个意思吗?

library(splitstackshape)
library(dplyr)

df %>%
  cSplit("column", ",")

输出是:

       column_1                         column_2          column_3
1:  apple juice                guava-peach juice melon apple juice
2: orange juice pineapple strawberry lemon juice              <NA>

样本数据:

df <- structure(list(column = structure(1:2, .Label = c("apple juice,guava-peach juice,melon apple juice", 
"orange juice,pineapple strawberry lemon juice"), class = "factor")), .Names = "column", row.names = c(NA, 
-2L), class = "data.frame")

推荐阅读