Y Zhang Y Zhang - 3 months ago 8
R Question

functional expression not work as column name in R

I try to add a new column to a data frame, with a specified column name.

This works:

dat = data.frame(x1 = 1:10,
x2 = 101:110,
x3 = 1:2,
x4 = 2:1)

cbind(dat, 'x10' = 1:10)


Result:

x1 x2 x3 x4 x10
1 1 101 1 2 1
2 2 102 2 1 2
3 3 103 1 2 3
4 4 104 2 1 4
5 5 105 1 2 5
6 6 106 2 1 6
7 7 107 1 2 7
8 8 108 2 1 8
9 9 109 1 2 9
10 10 110 2 1 10


but using a functional expression as the column name not work

cbind(dat, paste0('x10', '_flag') = 1:10)



Error: unexpected '=' in "cbind(dat, paste0('x10', '_flag') ="


I was thinking of

column_name = paste0('x10', '_flag')
cbind(dat, column_name = 1:10)


but it will take "column_name" as the column name, rather than the string it refers to (thanks @42- for correcting me)

How to let R know
paste0()
is just a string? I tried
as.character(paste0())
and it didn't work. Any help's appreciated. Thank you!

42- 42-
Answer

Rather than using cbind, you should learn to use "[", since it does accept calculated column names in the j-argument position (after the first comma):

> dat[ , paste0('x10', '_flag') ] = 1:10
> dat
   x1  x2 x3 x4 x10_flag
1   1 101  1  2        1
2   2 102  2  1        2
3   3 103  1  2        3
4   4 104  2  1        4
5   5 105  1  2        5
6   6 106  2  1        6
7   7 107  1  2        7
8   8 108  2  1        8
9   9 109  1  2        9
10 10 110  2  1       10

This is equivalent to a similar strategy with "[["

dat[[ paste0('x10', '_flag') ]] = 1:10

Note: this avoids unfortunate newbie efforts to get calculated column names assigned using $

Comments