使用子集中的范围字符()/从字符到数字的强制范围(Using the Character of a Range in Subset()/Coercing Range from Character to

编程入门 行业动态 更新时间:2024-10-12 22:31:06
使用子集中的范围字符()/从字符到数字的强制范围(Using the Character of a Range in Subset()/Coercing Range from Character to Numeric)

我正在努力让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]]) }

更多推荐

本文发布于:2023-08-07 13:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464535.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符   数字   Character   Range   Coercing

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!