[英]How to loop through mapply in R?
I am trying to concatenate strings using mapply
function in R.我正在尝试在 R 中使用
mapply
function 连接字符串。 However, I want one of the strings to be variable in mapply
function.但是,我希望其中一个字符串在
mapply
function 中是可变的。 I have a snippet of my code below:我在下面有一段代码:
strings<-data.frame(x=c("dsf","sdf","sdf"))
strings2<-data.frame(extension=c(".csv",".json",".xml"))
for (i in 1:3)
{
strings_concat<-mapply(function(string1,string2) paste0(string1,string2),strings$x,strings2$extension[i])%>%
data.frame()%>%
unlist()%>%
data.frame()
#dosomething with strings_concat
}
But this is giving me the last iteration only但这只是给我最后一次迭代
strings_concat
dsf.xml
sdf.xml
sdf.xml
bust instead, the desired output is as follows:相反,所需的 output 如下:
strings_concat
dsf.csv
sdf.csv
sdf.csv
dsf.json
sdf.json
sdf.json
dsf.xml
sdf.xml
sdf.xml
At every iteration, i want to combine strings_concat
with another dataframe and save it.在每次迭代中,我想将
strings_concat
与另一个 dataframe 组合并保存。 Can anyone help me if there is an easy way to do this in R?如果在 R 中有一种简单的方法可以帮助我吗?
Perhaps, outer
is a better option here:也许,在这里,
outer
是一个更好的选择:
strings_concat <- c(outer(strings$x, strings2$extension, paste0))
strings_concat
#[1] "dsf.csv" "sdf.csv" "sdf.csv" "dsf.json" "sdf.json" "sdf.json"
# "dsf.xml" "sdf.xml" "sdf.xml"
You can add it in a data.frame:您可以将其添加到 data.frame 中:
df <- data.frame(strings_concat)
If you want to add some additional steps at each iteration you can use lapply
:如果您想在每次迭代中添加一些额外的步骤,您可以使用
lapply
:
lapply(strings2$extension, function(x) {
strings_concat <- paste0(strings$x, x)
#do something with strings_concat
})
All you should need to do is make sure you are continually augmenting your dataset.您需要做的就是确保不断扩充数据集。 So I think this should do the trick:
所以我认为这应该可以解决问题:
strings<-data.frame(x=c("dsf","sdf","sdf"))
strings2<-data.frame(extension=c(".csv",".json",".xml"))
# We are going to keep adding things to results
results = NULL
for (i in 1:3)
{
strings_concat<-mapply(function(string1,string2) paste0(string1,string2),strings$x,strings2$extension[i])%>%
data.frame()%>%
unlist()%>%
data.frame()
# Here is where we keep adding things to results
results = rbind(results, strings_concat)
}
print(results)
Caution: not in front a computer with R so this code is untested注意:不要在带有 R 的计算机前,因此此代码未经测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.