frank
frank

Reputation: 3598

make new column in dataframe r by assign

I have a dataframe

A=data.frame(a=1:4,b=11:14)
> A
  a  b
1 1 11
2 2 12
3 3 13
4 4 14

and would like to be able to generate a new column based on the original, but would also like to have the name of the column based on them as well.

I would like the end result to be

> data.frame(A,ab)
  a  b ab
1 1 11 11
2 2 12 24
3 3 13 39
4 4 14 56

I tried

> assign(paste(colnames(A)[1],'someText',colnames(A)[2],sep=''),A$a*A$b)
> A
  a  b
1 1 11
2 2 12
3 3 13
4 4 14

to no avail. The assignation worked though

> asomeTextb
[1] 11 24 39 56

Note that I have 56 columns, and wanted to make the column names an indication of what I did to the columns, using loops and referencing via i and j. Basically:

for(i in 1:n){
    assign(paste(colnames(A)[i],'someText',colnames(A)[i-1],sep=''),A[,i]*A[,i-1])
}

Upvotes: 1

Views: 847

Answers (2)

joran
joran

Reputation: 173517

Try:

A=data.frame(a=1:4,b=11:14)
> A[[paste0(colnames(A)[1],colnames(A)[2])]] <- with(A,a*b)
> A
  a  b ab
1 1 11 11
2 2 12 24
3 3 13 39
4 4 14 56

...and forget that you ever heard of the function assign. Like, never use it again, or even really think about it. It is dead to you.

If you apply this to the for loop you sketched, be aware that starting your loop index at 1 and then referencing the column i-1 is going to cause problems. There is no column 0. You probably want to loop from 2 to n.

Upvotes: 4

Edu
Edu

Reputation: 903

An alternative approach with dplyr

A=data.frame(a=1:4,b=11:14)

library(dplyr)

AB = A %>% mutate(ab = a*b)

Upvotes: 0

Related Questions