Home > database >  How to convert dataframe to list in R
How to convert dataframe to list in R

Time:09-30

I am stuck at converting data frame to list in R

My hypothetical data frame looks like this

a<-data.frame(country = rep(c("Africa", "Asia","Europe"), length.out=9),
              Year = rep(1987:1989, each=3),
              GDP = (1:9),
              GNP=(11:19),
              PPP=(21:29))
> a
  country Year GDP GNP PPP
1  Africa 1987   1  11  21
2    Asia 1987   2  12  22
3  Europe 1987   3  13  23
4  Africa 1988   4  14  24
5    Asia 1988   5  15  25
6  Europe 1988   6  16  26
7  Africa 1989   7  17  27
8    Asia 1989   8  18  28
9  Europe 1989   9  19  29

I want to convert this data frame to a list which looks like this

[[1]]
  country Year GDP
1  Africa 1987   1
2    Asia 1987   2
3  Europe 1987   3
4  Africa 1988   4
5    Asia 1988   5
6  Europe 1988   6
7  Africa 1989   7
8    Asia 1989   8
9  Europe 1989   9

[[2]]
  country Year GNP
1  Africa 1987  11
2    Asia 1987  12
3  Europe 1987  13
4  Africa 1988  14
5    Asia 1988  15
6  Europe 1988  16
7  Africa 1989  17
8    Asia 1989  18
9  Europe 1989  19

[[3]]
  country Year PPP
1  Africa 1987  21
2    Asia 1987  22
3  Europe 1987  23
4  Africa 1988  24
5    Asia 1988  25
6  Europe 1988  26
7  Africa 1989  27
8    Asia 1989  28
9  Europe 1989  29

I am totally stuck at this point... :(

Could you help me do this in R?

CodePudding user response:

You can use lapply -

common_cols <- 1:2
lapply(names(a[-common_cols]), function(x) cbind(a[common_cols], a[x]))

#[[1]]
#  country Year GDP
#1  Africa 1987   1
#2    Asia 1987   2
#3  Europe 1987   3
#4  Africa 1988   4
#5    Asia 1988   5
#6  Europe 1988   6
#7  Africa 1989   7
#8    Asia 1989   8
#9  Europe 1989   9

#[[2]]
#  country Year GNP
#1  Africa 1987  11
#2    Asia 1987  12
#3  Europe 1987  13
#4  Africa 1988  14
#5    Asia 1988  15
#6  Europe 1988  16
#7  Africa 1989  17
#8    Asia 1989  18
#9  Europe 1989  19

#[[3]]
#  country Year PPP
#1  Africa 1987  21
#2    Asia 1987  22
#3  Europe 1987  23
#4  Africa 1988  24
#5    Asia 1988  25
#6  Europe 1988  26
#7  Africa 1989  27
#8    Asia 1989  28
#9  Europe 1989  29
  • Related