Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in R with key value

Tags:

loops

r

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]))
}
like image 822
Klaus Avatar asked Dec 11 '22 11:12

Klaus


2 Answers

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))
}
like image 177
chao Avatar answered Dec 30 '22 15:12

chao


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)
like image 28
f3lix Avatar answered Dec 30 '22 14:12

f3lix