dataframe row to string with column names

My df

name  age
tom    21
mary   42

How can I combine each row to something like

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

the output can be a list of strings.

728x90

3 Answers dataframe row to string with column names

Try with thispaste combination:

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

4 months ago

A more general approach using apply.

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

here is a super general version:

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"

4 months ago

I have some sample data, such as:

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

Data frame looking is as

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

Now make a list object and fill it.

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 = ":")
}

Finall, result is

> 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"

4 months ago