What is the equivalent way in R to
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
that means
arr<-c(a=1,b=2,c=3)
key<-names(arr)
val<-arr
for(i in 1:length(arr)){
print(paste(key[i],val[i]))
}
Assuming var
is a list of key value pairs, a more generic foreach loop can be achieved with the following snippet:
for(key in names(var)){
value<-var[key]
print(paste(key,'=',value))
}
With the foreach you can write:
foreach(key=names(arr), val=arr) %do% print(paste(key,val))
And you can define your own forkeyval
function:
forkeyval = function(arr, .combine=function(...){NULL}, ...) {
foreach(key=names(arr), val=arr, .combine=.combine, ...) }
Which lets you write:
forkeyval(arr) %do% print(paste(key,val)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With