R: constructing a data frame with many columns using paste()

前端 未结 2 970
萌比男神i
萌比男神i 2021-01-28 02:02
col1 <- c(1, 2, 3)
col2 <- c(4, 5, 6)
col3 <- c(7, 8, 9)
  • On the one hand data.frame(col1, col2, col3)

gives<

相关标签:
2条回答
  • 2021-01-28 02:11

    If we already have a string that have the objects pasted together, we can use strsplit to split the string and get the values with mget. This will return a list output. Then wrap it with data.frame to convert it to 'data.frame`

    data.frame(mget(strsplit(str1, ', ')[[1]])) 
    

    data

    str1 <- paste0("col", 1:3, collapse=", ")
    
    0 讨论(0)
  • 2021-01-28 02:12

    You may want to use mget

    do.call(cbind, mget(paste0("col", 1:3)))
    

    Where the paste0 generates the variable names, mget gets the associated values, and cbind puts them together into a data frame.

    0 讨论(0)
提交回复
热议问题