Klaus
Klaus

Reputation: 2056

For loop in R with key value

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]))
}

Upvotes: 6

Views: 5506

Answers (4)

ctbrown
ctbrown

Reputation: 2361

You can also use the kv() from the kv package. It is exceedingly light weight and departs very little from base R syntax.

for( . in kv(arr) ) {
  cat( "Key:", .$k, "Value:", .$v, "<br />\n" ) 
}

Disclosure: I wrote kv.

Upvotes: 0

chao
chao

Reputation: 2024

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))
}

Upvotes: 11

f3lix
f3lix

Reputation: 29877

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)

Upvotes: 3

flodel
flodel

Reputation: 89057

R likes to vectorize things. You can do:

sprintf("Key: %s; Value: %s", names(arr), arr)
# [1] "Key: a; Value: 1" "Key: b; Value: 2" "Key: c; Value: 3"

Or for a nicer output, pass it through cat:

cat(sprintf("Key: %s; Value: %s", names(arr), arr), sep = "\n")
# Key: a; Value: 1
# Key: b; Value: 2
# Key: c; Value: 3

Upvotes: 2

Related Questions