Insert i th vector number into data frame column name - R

不羁岁月 提交于 2020-01-21 17:19:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!