繁体   English   中英

R:如何重新连接数据框中的拆分字符串

[英]R: How to re-concatenate a split string in a data frame

我使用以下内容创建了一个数据框:

Student <- c("John Davis","Angela Williams","Bullwinkle Moose","David Jones",
"Janice Markhammer","Cheryl Cushing","Reuven Ytzrhak","Greg Knox","Joel England",
"Mary Rayburn")
Math <- c(502,600,412,358,495,512,410,625,573,522)
Science <- c(95,99,80,82,75,85,80,95,89,86)
English <- c(25,22,18,15,20,28,15,30,27,18)
student.exam.data <- data.frame(Student,Math,Science,English)

然后我通过student.exam.data$Student[1] <- strsplit(as.character(student.exam.data$Student[1]), " ", fixed = FALSE)将“John Davis”拆分为c("John", "Davis")

我现在试图将这两个字符重新连接成一个“John Davis”字符串。 我试过paste(student.exam.data$Student[1], collapse = " ") , paste(as.vector(student.exam.data$Student[1]), collapse = " ")toString(student.exam.data$Student[1]) 所有三个都返回"c(\\"John\\", \\"Davis\\")"

首先,为什么这些会返回反斜杠,其次,解决这个问题的合适方法是什么?

问题是这条线

student.exam.data$Student[1] <- strsplit(as.character(student.exam.data$Student[1]), " ", fixed = FALSE)

将数据框中的第一个变量转换为列表 ---

str(student.exam.data)
'data.frame':   10 obs. of  4 variables:
 $ Student:List of 10
..$ : chr  "John" "Davis"
..$ : chr "Angela Williams"
..$ : chr "Bullwinkle Moose"
..$ : chr "David Jones"
..$ : chr "Janice Markhammer"
..$ : chr "Cheryl Cushing"
..$ : chr "Reuven Ytzrhak"
..$ : chr "Greg Knox"
..$ : chr "Joel England"
..$ : chr "Mary Rayburn"
$ Math   : num  502 600 412 358 495 512 410 625 573 522
$ Science: num  95 99 80 82 75 85 80 95 89 86
$ English: num  25 22 18 15 20 28 15 30 27 18

因此,第一个元素有两个值。 这可以在回答您的问题的字面意义上重新组合 -

student.exam.data$Student[1]<-paste(student.exam.data$Student[1][[1]],student.exam.data$Student[1][[2]])

它没有做的是纠正你的第一个变量仍然是一个列表的事实。

您可能会发现使用tidyr::separate()unite()更方便。

例子:

library(tidyr)

student.exam.data %>% separate(Student, c('first_name','last_name')) -> d2

head(d2,3)

返回:

  first_name last_name Math Science English
1       John     Davis  502      95      25
2     Angela  Williams  600      99      22
3 Bullwinkle     Moose  412      80      18

同样地:

d2 %>% unite('full_name', first_name, last_name, sep=' ') -> d3

head(d3, 3)

返回:

         full_name Math Science English
1       John Davis  502      95      25
2  Angela Williams  600      99      22
3 Bullwinkle Moose  412      80      18

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM