将字符串拆分为单元格并将R中的单元格复用

时间:2018-03-04 19:38:27

标签: r

我想将字符串拆分为几个单元格,str拆分值为alt + enter,我尝试了strsplit函数,但它没有工作。

我的代码:

library(readxl)

hobiesTable <- read_xlsx("hobies.xlsx")

print(hobiesTable$hobies)

a <- strsplit(hobiesTable$hobies,'\r\n')
print(a)

我的表:

structure(list(name = c("Hila", "Adi", "Ido"), id = c(123, 122, 
258), hobies = c("Horses\r\nSwimming\r\nGolf", "Horses", "Golf"
), age = c(28, 29, 30)), .Names = c("name", "id", "hobies", "age"
), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, 
-3L))

我需要输出此表:

structure(list(name = c("Hila", "Hila", "Hila", "Adi", "Ido"), 
    id = c(123, 123, 123, 122, 258), hobies = c("Horses", "Swimming", 
    "Golf", "Horses", "Golf"), age = c(28, 28, 28, 29, 30)), .Names = c("name", 
"id", "hobies", "age"), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -5L))

先谢谢你了!

2 个答案:

答案 0 :(得分:2)

让你的表格为dat

library(tidytext) 
unnest_tokens(dat,hobies,hobies)
# A tibble: 5 x 4
   name    id   hobies   age
  <chr> <dbl>    <chr> <dbl>
1  Hila   123   horses    28
2  Hila   123 swimming    28
3  Hila   123     golf    28
4   Adi   122   horses    29
5   Ido   258     golf    30

答案 1 :(得分:1)

Tidyverse解决方案:

你需要这些库:

library(tidyr)
library(dplyr)

假设您正在使用数据框

# Your data
a <- data.frame(a)

a_unnest <- a %>% 
  mutate(hobies = strsplit(hobies, "\r\n")) %>%
  unnest(hobies)