首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否将R中的某些行拆分成多行?

是否将R中的某些行拆分成多行?
EN

Stack Overflow用户
提问于 2020-07-03 03:17:48
回答 2查看 374关注 0票数 1

有没有可能把这些数据..。

代码语言:javascript
运行
复制
Month      Animal        Number    CodeName
8-9       cat             2         whiskers
3-4       cat|dog         1|4       whiskers|spot
10-11     elephant        5         trunks
7-8       cat|snake       3|2       whiskers|thomas
5-6       elephant|dog    0|7       trunks|spot

到这个..。

代码语言:javascript
运行
复制
Month      Animal        Number    CodeName
8-9         cat           2         whiskers
3-4         cat           1         whiskers
3-4         dog           4         spot
10-11       elephant      5         trunks
7-8         cat           3         whiskers
7-8         snake         2         thomas
5-6         elephant      0         trunks
5-6         dog           7         spot

通过打破管子?

我将保持Month列不变,但是Animal、Number和CodeName管道列将被拆分。

我试过的最后一段代码是...

df %>% separate_rows(.,%>%,Number,CodeName,convert = TRUE)

但是我收到了“长度不兼容”的错误。

任何帮助都将不胜感激

EN

回答 2

Stack Overflow用户

发布于 2020-07-03 03:32:57

您可以在tidyr中使用separate_rows,但必须将sep参数正确指定为sep = "\\|"。请注意,您必须对|进行转义,因为在regrex中,它是一个特殊字符:

代码语言:javascript
运行
复制
df <- read.table(text = "Month      Animal        Number    CodeName
8-9       cat             2         whiskers
3-4       cat|dog         1|4       whiskers|spot
10-11     elephant        5         trunks
7-8       cat|snake       3|2       whiskers|thomas
5-6       elephant|dog    0|7       trunks|spot", header = TRUE, stringsAsFactors = FALSE)

library(dplyr)
library(tidyr)

df %>% separate_rows(Animal, Number, CodeName, sep = "\\|")
  Month   Animal Number CodeName
1   8-9      cat      2 whiskers
2   3-4      cat      1 whiskers
3   3-4      dog      4     spot
4 10-11 elephant      5   trunks
5   7-8      cat      3 whiskers
6   7-8    snake      2   thomas
7   5-6 elephant      0   trunks
8   5-6      dog      7     spot
票数 1
EN

Stack Overflow用户

发布于 2020-07-03 03:19:48

我们可以从splitstackshape使用cSplit

代码语言:javascript
运行
复制
library(splitstackshape)
cSplit(df, c("Animal", "Number", "CodeName"), sep="|", "long")
#  Month   Animal Number CodeName
#1:   8-9      cat      2 whiskers
#2:   3-4      cat      1 whiskers
#3:   3-4      dog      4     spot
#4: 10-11 elephant      5   trunks
#5:   7-8      cat      3 whiskers
#6:   7-8    snake      2   thomas
#7:   5-6 elephant      0   trunks
#8:   5-6      dog      7     spot

数据

代码语言:javascript
运行
复制
df <- structure(list(Month = c("8-9", "3-4", "10-11", "7-8", "5-6"), 
    Animal = c("cat", "cat|dog", "elephant", "cat|snake", "elephant|dog"
    ), Number = c("2", "1|4", "5", "3|2", "0|7"), CodeName = c("whiskers", 
    "whiskers|spot", "trunks", "whiskers|thomas", "trunks|spot"
    )), class = "data.frame", row.names = c(NA, -5L))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62703563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档