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

问题描述 投票:0回答:2

我想将字符串拆分为几个单元格,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))

先谢谢你!

r
2个回答
1
投票

一个Tidyverse解决方案:

你需要这些库:

library(tidyr)
library(dplyr)

假设您正在使用数据框

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

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

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
© www.soinside.com 2019 - 2024. All rights reserved.