1

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.

3 Answers 3

2

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"
Sign up to request clarification or add additional context in comments.

2 Comments

I like the use of apply let me try
ok I like it, it outputs to a vector of strings. Awesome! and then I'll work on pulling them apart and turning them back to a df
2

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

1 Comment

let me see if I can wrap that in apply so that I can do that without manually inputing each column
1

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"

1 Comment

also the paste is not general so what happens when there is a new column?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.