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

廉价感情. 提交于 2019-12-01 14:44:13

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

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!