How do you combine two columns into a new column in a dataframe made of two or more different csv files?

前端 未结 2 446
北恋
北恋 2021-01-17 01:27

I have several csv files all named with dates and for all of them I want to create a new column in each file that contains data from two other columns placed together. Then,

相关标签:
2条回答
  • 2021-01-17 01:38

    The object mydata is a list of data frames. You can change the data frames in the list with lapply:

    lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))
    

    file1 <- "a b             
    x 2 3"    
    file2 <- "a b
    x 3 1"
    mydata <- lapply(c(file1, file2), function(x) read.table(text = x, header =TRUE))
    lapply(mydata, function(x) "[<-"(x, "c", value = paste0(x$a, x$b)))
    
    # [[1]]
    #   a b  c
    # x 2 3 23
    # 
    # [[2]]
    #   a b  c
    # x 3 1 31
    
    0 讨论(0)
  • 2021-01-17 01:55

    You can use rbind (data1,data2)[,c(1,3)] for that. I assume that you can create col d in each dataframe which is a basic thing.

     data1<-structure(list(a = 1:2, b = 2:3, c = c(3L, 1L), d = c(13L, 21L
        )), .Names = c("a", "b", "c", "d"), row.names = c("x", "y"), class = "data.frame")
    
     > data1
          a b c  d
        x 1 2 3 13
        y 2 3 1 21   
    
    data2<-structure(list(a = c(3L, 2L), b = c(2L, 1L), c = c(1L, 3L), d = c(31L, 
    23L)), .Names = c("a", "b", "c", "d"), row.names = c("x", "y"
    ), class = "data.frame")
    
    > data2
      a b c  d
    x 3 2 1 31
    y 2 1 3 23
    
    data3<-rbind(data1,data2)
    
        > data3
       a b c  d
    x  1 2 3 13
    y  2 3 1 21
    x1 3 2 1 31
    y1 2 1 3 23
    
    finaldata<-data3[,c("a","d")]
        > finaldata
       a  d
    x  1 13
    y  2 21
    x1 3 31
    y1 2 23
    
    0 讨论(0)
提交回复
热议问题