[R] list를 data.frame의 column으로 추가하는 예제
list를 data.frame의 새로운 컬럼으로 추가하는 예제이다.
> num.iters <- 5
> list1 <- vector('list', num.iters)
>
> for (i in 1:num.iters) {
+ list1[[i]] <- as.integer(2)
+ names(list1)[i] <- paste('XX', i, sep='.')
+ }
> do.call(cbind, list1)
XX.1 XX.2 XX.3 XX.4 XX.5
[1,] 2 2 2 2 2
>
> df <- data.frame(x<-rep.int(1, 5))
> df$xx <- sapply(list1, as.numeric)
>
> str(df) #숫자인지 판별.
'data.frame': 5 obs. of 2 variables:
$ x....rep.int.1..5.: num 1 1 1 1 1
$ xx : num 2 2 2 2 2
> rowSums(df)
[1] 3 3 3 3 3
> max(df)
[1] 2
주의 할 점은 하나의 컬럼으로 합칠 때, as.numeric대신 paste0 함수를 사용하면 character가 만들어진다.!!
>df$xx <- sapply(list1, as.numeric)
> str(df) #숫자인지 판별.
'data.frame': 5 obs. of 2 variables:
$ x....rep.int.1..5.: num 1 1 1 1 1
$ xx : num 2 2 2 2 2
> df$xx <- sapply(list1, paste0)
> str(df) #숫자인지 판별.
'data.frame': 5 obs. of 2 variables:
$ x....rep.int.1..5.: num 1 1 1 1 1
$ xx : chr "2" "2" "2" "2" ...