[英]Refer to the last column in R
I am trying to do some manipulation on the last column in a generic way.我正在尝试以通用方式对最后一列进行一些操作。
I found here on the forums this nice piece of code that returns the name of the last columns:我在论坛上找到了这段不错的代码,它返回最后一列的名称:
tail(names(train),1) #returns [1] "last"
I still can't figure out how to reference directly to my dataset's last columns as:我仍然不知道如何直接引用我的数据集的最后一列:
data$last
只需使用ncol()
获取最后一个 col 的索引
data[,ncol(data)]
Take the first element of the rev
ersed vector of column names:采取的第一个元素
rev
列名的ersed向量:
rev(names(mtcars))[1]
[1] "carb"
Similarly, to get the last column, you can use同样,要获取最后一列,您可以使用
rev(mtcars)[1]
参考最后一栏:
colnames(data)[ncol(data)]
我更喜欢@Troy 的解决方案,这是另一种方式:
train[, tail(colnames(train), 1)]
Troy's answer is simpler, and can be adapted to refer to "n" elements before the last column, using the ":" operator. Troy 的答案更简单,可以使用“:”运算符修改为引用最后一列之前的“n”个元素。
If you want to refer to the last threee columns, you could write:如果你想参考最后三列,你可以写:
data[,ncol(data)] # refers to the last column
data[,(ncol(data)-2):ncol(data)] # refers to the three last columns
Function last_col()
from tidyselect
package may help. tidyselect
包中的last_col()
函数可能会有所帮助。 See also answer here另请参阅此处的答案
https://stackoverflow.com/a/44353413 https://stackoverflow.com/a/44353413
You can use tail
, but you have to coerce to list:您可以使用
tail
,但您必须强制列出:
tail(as.list(mtcars), 1)
This will return a vector with the contents of the column.这将返回一个包含列内容的向量。 If you want to preserve the structure, you can use:
如果要保留结构,可以使用:
utils:::tail.default(mtcars, 1)
so that tail
treats the input like a list.所以
tail
将输入视为列表。 The only reason really to use this approach over Troy's are if you want more than just the last column (ie last N), where it becomes a lot easier to do it this way.真正在 Troy 上使用这种方法的唯一原因是,如果您想要的不仅仅是最后一列(即最后 N 列),那么以这种方式进行操作会变得容易得多。
Here's an example of indexing just the last column name.下面是仅索引最后一列名称的示例。 Reference the
names(df1[,ncol(df1)])
:引用
names(df1[,ncol(df1)])
:
df1 <- df1 %>%
add_column(new1 = NA, new2 = NA, new3 = NA, .after = names(df1[,ncol(df1)]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.