[英]A more efficient way to strip a character from column names in an R dataframe?
I want to strip the X's from the column names in this R data frame.我想从这个 R 数据框中的列名中删除 X。
> d
days X2000 X2001 X2002 X2003
1 June-01 90 85 88 75
2 June-02 93 84 88 81
3 June-03 94 83 85 83
Here's what I've got so far.这是我到目前为止所得到的。 It gets me the column names that I want, by taking the substring of each of the columns 2 through 5.
它通过获取第 2 到第 5 列的 substring 得到我想要的列名。
> new_colnames <- c()
> for (name in colnames(d[2:5])) { new_colnames <- c(new_colnames, substring(name, 2)) }
> colnames(d) <- c('days', new_colnames)
> d
days 2000 2001 2002 2003
1 June-01 90 85 88 75
2 June-02 93 84 88 81
3 June-03 94 83 85 83
Is there a more efficient way of doing this?有没有更有效的方法来做到这一点? What is "best practice"?
什么是“最佳实践”?
As someone already suggested above, you just need to use the sub
command.正如上面已经有人建议的那样,您只需要使用
sub
命令。 I recreated your database above and did just this:我在上面重新创建了您的数据库并这样做了:
# Load piping library:
library(tidyverse)
# Create days variable:
days <- c("June-01",
"June-02",
"June-03")
# Create year variables:
X2000 <- c(90,93,94)
X2001 <- c(85,84,83)
X2002 <- c(88,88,85)
X2003 <- c(75,81,83)
# Make data frame with variables:
df <- data.frame(days,
X2000,
X2001,
X2002,
X2003)
At this point you should have the same data frame as what you have above:此时,您应该拥有与上面相同的数据框:
Xdays X2000 X2001 X2002 X2003
1 June-01 90 85 88 75
2 June-02 93 84 88 81
3 June-03 94 83 85 83
From here you just need to change the names:从这里您只需要更改名称:
# Change names:
names(df) <- sub("X", "", names(df))
# Print:
df
This should print this new table:这应该打印这个新表:
days 2000 2001 2002 2003
1 June-01 90 85 88 75
2 June-02 93 84 88 81
3 June-03 94 83 85 83
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.