Assign a column of a data.frame with string name in R

后端 未结 3 1780
一向
一向 2020-12-29 09:21

I am trying to assign data to an existing dataframe with a name generated in a loop. A basic example might be

A = data.frame(a = c(1,2,3), b=c(3,6,2))

for          


        
相关标签:
3条回答
  • 2020-12-29 09:54

    Maybe you want this:

    R> A <- data.frame(a=c(1,2,3), b=c(3,6,2))
    R> colnames(A) <- paste("Names", 1:ncol(A), sep="")
    R> A
      Names1 Names2
    1      1      3
    2      2      6
    3      3      2
    R> 
    

    but as Tyler said in the comment, it is not entirely clear what you are asking.

    0 讨论(0)
  • 2020-12-29 09:57

    Still not entirely sure what you're trying to accomplish:

    A = data.frame(a = c(1,2,3), b=c(3,6,2))
    B <- data.frame(A, c(6, 3, 2), c(6, 3, 2))
    names(B)[3:4] <- paste0("name", 1:2)
    B
    

    Which yields:

      a b name1 name2
    1 1 3     6     6
    2 2 6     3     3
    3 3 2     2     2
    
    0 讨论(0)
  • 2020-12-29 10:15

    The other answers are good, but if you are set on using a loop like you have, then this would work:

    A <- data.frame(a = c(1,2,3), b = c(3,6,2))
    
    for (i in 1:2){
        A[paste("Name", i, sep="")] <- c(6,3,2)
    }
    

    which gives

    > A
      a b Name1 Name2
    1 1 3     6     6
    2 2 6     3     3
    3 3 2     2     2
    

    Alternatively, paste("Name", i, sep="") could be replaced with paste0("Name", i)

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