r - 计算数据框列中的元素,然后在 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,",")
不幸的是,我没有得到我想要的。感谢您的帮助。
解决方案
你是这个意思吗?
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")
推荐阅读
- python - 在 mathplotlib 中沿 Z 轴移动 asix 标签
- c# - Linq 代码未在 aspx 页面中编译 (IIS 10/.ASP .NET 4.7.2)
- jmeter - jmeter记录器:如何在不创建新项目的情况下清除并重新开始记录
- python - 具有独立索引的动态数据透视表
- android - 为什么添加listView显示数据后应用崩溃
- reactjs - SVG 以错误的颜色显示
- php - 有时在脚本执行中数据库正在更新
- javascript - 如何检测 D3 v5(文本重叠)中的元素冲突
- c - 当大括号括起来的列表中的初始值设定项少于聚合的元素或成员时,C 编译器如何声明数组?
- python - 如何将 CSV 转换为固定宽度的文本文件?