[英]Renaming a column of data frame as a number (in R)
I am looking at 10 different runners, running 10 laps. 我正在寻找10个不同的跑步者,跑10圈。 For each runner, after each lap, I have total used time.
对于每个跑步者,每圈后,我有总的使用时间。 For simplicity lets say the data frame looks like this:
为简单起见,我们假设数据框如下所示:
> data<-data.frame(runner=c(1:10),lap1=c(1:10),lap2=c(2:11),...,lap10=c(10:20))
The lap times does not make any sense, this is just for the example. 单圈时间没有任何意义,这只是一个例子。
Now, I am creating a function, where one of the arguments of the function is the lap number c: 现在,我正在创建一个函数,其中函数的一个参数是圈数c:
> func<-function(a,b,c,...) { }
The parameters a and b, and the list (...)
of the function argument is not relevant for my question, but the lap number c
is. 参数a和b以及函数参数的
list (...)
与我的问题无关,但是圈数c
是。 When I call my function with the argument c
, it needs to be a number between 1 and 10. 当我用参数
c
调用我的函数时, 它需要是1到10之间的数字。
Now, when I call my function with some argument c, for example c=4, I want to remove the columns called lap1, lap2, lap3, lap5,...,lap10
. 现在,当我用一些参数c调用我的函数时,例如c = 4,我想删除名为
lap1, lap2, lap3, lap5,...,lap10
。 So basically I need R to recognize that the argument c
equals 4, and then proceeding to remove the columns I am not interested in. I cannot rename the columns. 所以基本上我需要R来识别参数
c
等于4,然后继续删除我不感兴趣的列。我不能重命名列。
Thank you for any help! 感谢您的任何帮助!
You can use paste0
to combine a string and a number to a new string: 您可以使用
paste0
将字符串和数字组合到一个新字符串:
num <- 4
s <- paste0("lap", num)
# [1] "lap4"
Now, you can remove all but the corresponding column: 现在,您可以删除除相应列之外的所有列:
data <- data[s]
Okay, so comments got out of hand, here is my answer: 好的,所以评论失控,这是我的答案:
getLapData <- function(data, c) data[c(1, grep(paste0("Lap", c, "_"), names(data)))]
getLapData(data, 1)
Produces: 生产:
# Runner Lap1_test Lap1_real
# 1 Runner 1 2.93 2.19
# 2 Runner 2 2.73 2.58
# 3 Runner 3 1.88 2.2
# 4 Runner 4 1.38 1.06
# 5 Runner 5 1.16 1.79
# 6 Runner 6 2.17 1.21
# 7 Runner 7 1.14 1.05
# 8 Runner 8 2.06 2.68
# 9 Runner 9 1.94 1.65
# 10 Runner 10 1.1 1.59
And here is the data I used: 以下是我使用的数据:
data <- as.data.frame(cbind(runner=paste("Runner", 1:10), replicate(20, round(runif(10, 1, 3), 2))))
names(data) <- c("Runner", paste0("Lap", rep(1:10, each=2), c("_test", "_real")))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.