0

Hello I would like to select rows in form of list from a dataframe. Here is my dataframe:

df2 <- data.frame("user_id" = 1:2, "username" = c(215,154), "password" = c("John4","Dora4"))

now with this dataframe I can only select 1 column to view rows as a list, which I did with this code

df2[["user_id"]]

output is

[1] 1 2

but now when I try this with more columns I am told its out of bounds, what is the problem here

df2[["user_id", "username"]]

How can I resolve and get the results of rows as a list

slava-kohut
  • 4,203
  • 1
  • 7
  • 24
LivingstoneM
  • 1,088
  • 10
  • 28

3 Answers3

0

If I understood your question correctly, you need to familiarize yourself with subsetting in R. These are ways to select multiple columns in R:

df2[,c('user_id', 'username')]

or

df2[,1:2]

If you want to return all columns as a list, you can use something like this:

lapply(1:ncol(df2), function(x) df2[,x])
slava-kohut
  • 4,203
  • 1
  • 7
  • 24
0

The format is df2['rows','columns'], so you should use:

df2[,c("user_id", "username")]

To get them 'in form of list', do:

as.list(df2[,c("user_id", "username")])

The double bracket [[ notion is used to select a single unnamed element (in this case a single unnamed column since data frames are essentially lists of column data).

See this answer for more on double vs single bracket notion: https://stackoverflow.com/a/1169495/8444966

rookie
  • 641
  • 5
  • 9
0

This should give you a row of list (There's got to be an answer somewhere here).

row_list<- as.list(as.data.frame(t(df2[c("user_id", "username")])))

#$V1
#[1]   1 215

#$V2
#[1]   2 154

If you want to keep names of the rows.

df2_subset <- df2[c("user_id", "username")]
setNames(split(df2_subset, seq(nrow(df2_subset))), rownames(df2_subset))
#$`1`
#  user_id username
#1       1      215

#$`2`
#  user_id username
#2       2      154
deepseefan
  • 3,701
  • 3
  • 18
  • 31