微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用标签作为新列的值将列表转换为数据框使用 R

如何解决使用标签作为新列的值将列表转换为数据框使用 R

我有一个这样的列表:

require(tidyverse)
months <- c("january","february","march","october","december") 
weekdays <- c("Sunday","Monday","Tuesday")
seasons <- c("Summer","Winter","Fall","autumn")
timeWords_list <- tibble::lst(months,weekdays,seasons)

我想将此列表转换为两列-data.frame: 我需要列表的所有值都在第一列中 并且标签是第二列的值

结果应该是这样的:

df <- data.frame(first_column  = c("january","december","Sunday","Tuesday","Summer","autumn"),second_column = c("months","months","weekdays","seasons","seasons"))

第二列可以是字符串或因子,但应对应于列表的标签。请注意,列表可能有不同的大小,其元素可能有不同的长度。

解决方法

一个简单的选项是 stack 来自 base R

df1 <- stack(timeWords_list)
names(df1) <- c("first_column","second_column")
,

我认为 @akrunstack 方法是迄今为止最有效的方法。这是另一个使用 unlist + rep

的基本 R 选项
data.frame(
  first_col = unlist(timeWords_list,use.names = FALSE),second_col = rep(names(timeWords_list),lengths(timeWords_list))
)

给出

   first_col second_col
1    january     months
2   february     months
3      march     months
4    october     months
5   december     months
6     Sunday   weekdays
7     Monday   weekdays
8    Tuesday   weekdays
9     Summer    seasons
10    Winter    seasons
11      Fall    seasons
12    autumn    seasons
,

使用 tibble::enframetidyr::unnest

tibble::enframe(timeWords_list,name = 'first_column',value = 'second_column') %>%
  tidyr::unnest(second_column)

# first_column second_column
#   <chr>        <chr>        
# 1 months       january      
# 2 months       february     
# 3 months       march        
# 4 months       october      
# 5 months       december     
# 6 weekdays     Sunday       
# 7 weekdays     Monday       
# 8 weekdays     Tuesday      
# 9 seasons      Summer       
#10 seasons      Winter       
#11 seasons      Fall         
#12 seasons      autumn       

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。