R:For循环在列表上工作,而不是单个元素
我试图通过编写函数来学习。它应该将计量单位转换为标准计量单位的一部分。在这种情况下,1/10或0.1 我试图循环遍历从strsplit生成的列表,但我只得到整个列表,而不是列表中的每个元素。我不知道我做错了什么。strsplit是错误的函数吗?我不认为问题出在strsplit中,但我不知道我在For循环中做错了什么:R:For循环在列表上工作,而不是单个元素,r,for-loop,R,For Loop,我试图通过编写函数来学习。它应该将计量单位转换为标准计量单位的一部分。在这种情况下,1/10或0.1 我试图循环遍历从strsplit生成的列表,但我只得到整个列表,而不是列表中的每个元素。我不知道我做错了什么。strsplit是错误的函数吗?我不认为问题出在strsplit中,但我不知道我在For循环中做错了什么: qty<-0 convf<-0 uom <- "EA" std <- "CA" pack <-"1EA/10CA" if(uom!=std){
qty<-0
convf<-0
uom <- "EA"
std <- "CA"
pack <-"1EA/10CA"
if(uom!=std){
s<-strsplit(pack,split = '/')
for (i in s){
print(i)
if(grep(uom,i)){
qty<- regmatches(i,regexpr('[0-9]+',i))
}
if(grep(std,i)){
convf<-regmatches(i, regexpr('[0-9]+',i))
}
} #end for
qty<-as.numeric(qty)
convf<-as.numeric(convf)
}
return(qty/convf)
qty可能是列表索引的问题。您是否尝试在strsplit
函数之后使用[[1]]
例如:
string <- "Hello/world"
mylist <- strsplit(string, "/")
## [[1]]
## [1] "Hello" "World"
string <- "Hello/World"
mylist <- strsplit(string, "/")[[1]]
## [1] "Hello" "World"
希望这能帮助你解决问题。这里有一些问题。您遇到的主要问题是s
是长度为1的列表。在该列表中,第一个(唯一)元素是长度为2的向量。因此,您需要在s[[1]]
中设置i
然而,我们可以更进一步。请尝试以下代码:
library(stringr)
lapply(strsplit(pack,split = '/'), # works within the list, can handle larger vectors for `pack`
function(x, uom, std) {
reg_expr <- paste(uom,std, sep = "|") # call this on its own, it's just searching for the text saved in uom or std
qty <- as.numeric(str_remove(x, reg_expr)) # removes that text and converts the string to a number
names(qty) <- str_extract(x, reg_expr) # extracts the text and uses it to name elements in qty
qty[uom] / qty[std] # your desired result.
},
uom = uom, # since these are part of the function call, we need to specify what they are. This is where you should change them.
std = std)
库(stringr)
lapply(strsplit(pack,split='/'),#在列表中工作,可以处理'pack'的较大向量`
函数(x,uom,std){
reg_expr我不知道这是否是您试图练习的内容,但在从“1EA/10CA”之类的字符串中提取数字时,我会避免循环。如果有帮助,则列lst
实际上是数据集中的一个列表
library(magrittr)
ds <- data.frame(pack = c("1EA/10CA", "1EA/4CA", "2EA/2CA"))
pattern <- "^(\\d+)EA/(\\d+)CA$"
ds %>%
dplyr::mutate(
qty = as.numeric(sub(pattern, "\\1", pack)),
convf = as.numeric(sub(pattern, "\\2", pack)),
ratio = qty / convf,
lst = purrr::map2(qty, convf, ~list(qty=.x[[1]], convf=.y[[1]]))
)
抱歉,忘记提到输出是一个列表=[1,1]
pack qty convf ratio lst
1 1EA/10CA 1 10 0.10 1, 10
2 1EA/4CA 1 4 0.25 1, 4
3 2EA/2CA 2 2 1.00 2, 2