数据框行到包含列名的字符串

时间:2018-11-09 13:22:56

标签: r dataframe

我的df

name  age
tom    21
mary   42

如何将每一行合并为类似的内容

name:tom,age:21
name:mary,age:42

输出可以是字符串列表。

3 个答案:

答案 0 :(得分:2)

尝试使用这种paste组合:

df$new.col <- paste(paste(colnames(df)[1], df$name, sep = ":"),
                    paste(colnames(df)[2], df$age, sep = ":"),
                    sep = ",")
# output
#  name age          new.col
#1  tom  21  name:tom,age:21
#2 mary  42 name:mary,age:42

答案 1 :(得分:1)

使用apply的更通用的方法。

apply(df1, 1, function(x) {n <- names(df1); paste0(n[1],":",x[1],",", n[2],":",x[2], collapse = "")})

这是一个超级通用的版本:

df1<-
structure(list(name = c("tom", "mary"), age = c(21L, 42L), cool = c("yes", 
"no")), row.names = c(NA, -2L), class = "data.frame")

apply(
    apply(df1, 1, function(x) {n <- names(df1); paste0(paste(n,x, sep = ":"))}),
    2,
    paste0, collapse = ","
)

# "name:tom,age:21,cool:yes" "name:mary,age:42,cool:no"

答案 2 :(得分:1)

我有一些示例数据,例如:

name=c("ali","asgar","ahmad","aslam","alvi")
age=c(12,33,23,16,34)
mydf=data.frame(name,age)

数据框外观为

> mydf
   name age
1   ali  12
2 asgar  33
3 ahmad  23
4 aslam  16
5  alvi  34

现在创建一个列表对象并填充它。

mylist=list()
for(i in 1:nrow(mydf))
{
  a=as.integer(mydf$age[i])
  n=as.String(mydf$name[i])
  mylist[i]=paste(paste(paste("name",n,sep = ":"),"age",sep = ","),a,sep = ":")
}

最后,结果是

> mylist
[[1]]
[1] "name:ali,age:12"

[[2]]
[1] "name:asgar,age:33"

[[3]]
[1] "name:ahmad,age:23"

[[4]]
[1] "name:aslam,age:16"

[[5]]
[1] "name:alvi,age:34"