我正在努力让subset()函数使用一个范围(即4:7),它被称为变量中的一个字符。
有没有办法让我强制输入,即变量DayVar,并且我希望函数子集的不同日期是数字,同时避免以下问题:
1.)保持4:7而不是4,5,6,7和
2.)将字符“1:4”转换为数字格式,子集评估可以使用它,就像它是1:4一样。
这是一个示例数据框:
DayVar = c("1", "2", "3", "4:7") a <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") b <- c(61:70) Day <- c(1:10) df <- data.frame("a" = a, "b" = b, "Day" = Day) Subset <- list() for(i in 1:length(DayVar)){ Subset[[i]] = subset(df, Day %in% DayVar[i]) }I'm struggling with having the subset() function use a range (i.e. 4:7) that is being called as a character from a variable.
Is there a way for me to coerce the input, which is the variable DayVar and has different days I want the function to subset, to be numeric while avoiding the following issues:
1.) keeping the 4:7 as such instead of as 4, 5, 6, 7, and
2.) converting the character "1:4" into numeric format that the subset evaluation can use as though it were 1:4.
Here is a sample data frame:
DayVar = c("1", "2", "3", "4:7") a <- c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") b <- c(61:70) Day <- c(1:10) df <- data.frame("a" = a, "b" = b, "Day" = Day) Subset <- list() for(i in 1:length(DayVar)){ Subset[[i]] = subset(df, Day %in% DayVar[i]) }最满意答案
由于thelatemail建议列表有效,但您必须更改DayVar引号以获取列表索引:
DayVar <- list(1,2,3,4:7) Subset <- list() for(i in 1:length(DayVar)){ Subset[[i]] = subset(df, Day %in% DayVar[[i]]) }As thelatemail suggested the list works but you have to change the DayVar quotes to get the list index:
DayVar <- list(1,2,3,4:7) Subset <- list() for(i in 1:length(DayVar)){ Subset[[i]] = subset(df, Day %in% DayVar[[i]]) }更多推荐
发布评论