问题
This is likely a quick fix! I am trying to place the ith position of my vector into my data frame column name. I am trying to use paste0 to enter the ith number.
sma <- 2:20
> sma
[1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# Place i number from sma vector to data frame column name
spx.sma <- df$close.sma.paste0("n", sma[i])
Column name should read:
"close.sma.n2"
If I print
paste0("n", sma[i])
I obtain:
> paste0("n", sma[i])
[1] "n2"
So really if i paste this into my data frame column name then it should read:
close.sma.n2
What is the correct method to achieve this?
I achieve the error:
> spx.sma <- df$close.sma.paste0(".n", sma[i])
Error: attempt to apply non-function
回答1:
You should treat the dataframe as a list. So avoid the "$" operator and instead use [[]].
so:
spx.sma <- df[[paste0("close.sma.n", sma[i])]]
来源:https://stackoverflow.com/questions/47142911/insert-i-th-vector-number-into-data-frame-column-name-r