Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
297 views
in Technique[技术] by (71.8m points)

twitter - Is there some way to split a list into its elements in R?

So I am doing an analysis of tweets from different accounts using get_timeline from rtweet. It returns a df with 90 variables, which is great. However, one of them, the variable hashtags, gives me either NA (no hashtags used in the tweet, one hashtag or a list of all the hashtags. So, I want to create different variables for each of the hashtags in order to save the tweets into a CSV to use powerBI and do some graphs. Thefore, my question is can you split all the elements of the list into different variables containing a single word each?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As I understand your problem you do not need to split the list in order to get all single or unique list entries, but use a combination of unlist and unique instead.

Let's assume you have a list of hashtags (just letters in the example) with different lengths, l_hashtags . Some hashtags are repetitions.

unlisting the list will give you vector with all hashtags, including all repetitions.

applying unique to this unlisted l_hastag gives you the unique members of the original list.

l_hashtags <- list(c(LETTERS[1:2]), rep(NA,5), LETTERS[5:15], c('A', 'N', 'N', 'J', 'K'))
l_hashtags
#> [[1]]
#> [1] "A" "B"
#> 
#> [[2]]
#> [1] NA NA NA NA NA
#> 
#> [[3]]
#>  [1] "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O"
#> 
#> [[4]]
#> [1] "A" "N" "N" "J" "K"

table(unlist(l_hashtags))
#> 
#> A B E F G H I J K L M N O 
#> 2 1 1 1 1 1 1 2 2 1 1 3 1

l_hashtags_unlisted <- unlist(l_hashtags)

unique(l_hashtags_unlisted)
#>  [1] "A" "B" NA  "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O"

You can of course put all this into one single line:

unique(unlist(l_hashtags))
# [1] "A" "B" NA  "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.7k users

...