【问题标题】:R convert list to stringR将列表转换为字符串
【发布时间】:2020-11-13 09:55:04
【问题描述】:

我有一个列表,我需要每个单独的元素作为一个字符。

 > str(df_data2)
 'data.frame':  2 obs. of  4 variables:
 $ retweet_count: int  21 31
 $ quote_count  : int  NA NA
 $ reply_count  : int  NA NA
 $ hashtags     :List of 2
 ..$ : chr  "BigData" "DataScience"
 ..$ : chr  "python" "neuralnetworks"

该列表的行数与数据集相同,但是,我希望每个组件都有字符串值。

 > str(df_data2)
 'data.frame':  2 obs. of  4 variables:
 $ retweet_count: int  21 31
 $ quote_count  : int  NA NA
 $ reply_count  : int  NA NA
 $ hashtags     : chr "BigData DataScience" "python neuralnetworks"

我该怎么做?

【问题讨论】:

  • 请使用dput()发布您的示例数据。
  • @MartinGal 使用unnest 将为列表的每个元素创建一个新行。
  • @IanCampbell 自己捂脸。好点子!
  • @MartinGal 我觉得应该有一个tidyr::hoist 选项,但我想不通。
  • @IanCampbell 我也不是。至少不是一行。我最好的方法是unnest_widerunite 连接。但是你已经给出了一个不错的解决方案。

标签: r list type-conversion character


【解决方案1】:

你可以使用sapply:

df_data2$hashtags <- sapply(df_data2$hashtags, paste, collapse = " ")

或者您也可以使用purrrdplyr

library(dplyr)
library(purrr)
df_data2 %>%
  mutate(hashtags = map_chr(hashtags, paste, collapse = " "))
  retweet_count quote_count reply_count              hashtags
1            21          NA          NA   BigData DataScience
2            31          NA          NA python neuralnetworks

样本数据

df_data2 <- structure(list(retweet_count = c(21, 31), quote_count = c(NA_real_, 
NA_real_), reply_count = c(NA_real_, NA_real_), hashtags = list(
    c("BigData", "DataScience"), c("python", "neuralnetworks"
    ))), row.names = c(NA, -2L), class = "data.frame")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多