For loop in R with key value - 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]))
}

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)

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

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.

Related

Testing whether a value is equal to a string value when it can also be NULL

I have a value which can be one of 3 strings, or NULL. When the value is NULL the following code does not work
value <- NULL
if( value == "test" ){
print("1")
} else {
print("2")
}
It seems I have to write the code as below to make it work:
if ( !is.null(value) && value== "test" ) {
print("1")
} else {
print("2")
}
Writing it like that however seems unnecessarily complicated and messy.
Is there a cleaner way to do this?
You could surround the condition with isTRUE()
value <- NULL
if ( isTRUE(value == "test") ) {
print("1")
} else {
print("2")
}
# [1] "2"
or replace == with identical():
identical(value, "test")
# [1] FALSE
You can use function setequal in base R:
value <- NULL
setequal(value, "test")
[1] FALSE
How about using %in% operator:
if( "test" %in% value){
print("1")
} else {
print("2")
}
[1] "2"

Passing tables as parameters in Nim

hopefully an easy question.. I've been playing around with Nim and have realised I need to pass a table (dictionary, map, in some other languages), but I can't seem to figure out the syntax for declaring it in doStuff()
import tables
proc doStuff(n:int, t:[int, int]) = # How should I declare 't' here?
if n == 0:
return
t[n] = (n * 10)
echo "length of t = " & ($len(t))
doStuff(n+1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & ($len(tbl))
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & ($len(tbl))
main()
The above gets me Error: type expected, but got: [int, int]
Sorry if this is basic, but my Googling hasn't given me an answer yet
Many TIA
You almost got it, it should be like below:
import tables
proc doStuff(n: int, t: var Table[int, int]) =
if n == 0:
return
t[n] = n * 10
echo "length of t = " & $len(t)
doStuff(n + 1, t)
proc main() =
var tbl = initTable[int, int]()
echo "length of tbl = " & $len(tbl)
tbl[0] = 0
doStuff(5, tbl)
echo "length of tbl = " & $len(tbl)
main()
You have to use var Table[int, int] instead of Table[int, int] because you are mutating the tbl variable recursively, so you need to pass by reference instead of by value.

Writing function with an if statement which executes when the statement is NULL or a string equivalent

I would like to have an if statement which executes when the statement is NULL or a string equivalent:
somefun <- function (number1, number2, type=NULL) {
if (is.null(type) | type == "sum") {
print(number1+number2)
} else if (type == "product") {
print(number1*number2)
}}
# So that the two following lines lead to the same result
somefun(1,4)
somefun(1,4,type="sum")
The first one however gives the error:
Error in if (is.null(type) | type == "sum") { :
argument is of length zero
How should I write the syntax?
This is one of those instances where you need to use || over |
somefun <- function (number1, number2, type=NULL) {
if (is.null(type) || type == "sum") {
print(number1+number2)
} else if (type == "product") {
print(number1*number2)
}
}
> somefun(1,4,type="sum")
[1] 5
> somefun(1,4,type=NULL)
[1] 5
> somefun(1,4)
[1] 5
If I can make a suggestion though:
somefun2 <- function (number1, number2, type=NULL){
if(is.null(type)){
type <- "sum"
}
switch(type,
"sum" = number1 + number2,
"product" = number1 * number2
)
}

Swift Dictionary Filter

So it looks like the filter function on a Swift (2.x) dictionary returns a tuple array. My question is there an elegant solution to turning it back into a dictionary? Thanks in advance.
let dictionary: [String: String] = [
"key1": "value1",
"key2": "value2",
"key3": "value3"
]
let newTupleArray: [(String, String)] = dictionary.filter { (tuple: (key: String, value: String)) -> Bool in
return tuple.key != "key2"
}
let newDictionary: [String: String] = Dictionary(dictionaryLiteral: newTupleArray) // Error: cannot convert value of type '[(String, String)]' to expected argument type '[(_, _)]'
If you are looking for a more functional approach:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { (var aggregate, elem) in
aggregate[elem.0] = elem.1
return aggregate
}
reduce here is used to construct a new dictionary from the filtered tuples.
Edit: since var parameters has been deprecated in Swift 2.2, you need to create a local mutable copy of aggregate:
let result = dictionary.filter {
$0.0 != "key2"
}
.reduce([String: String]()) { aggregate, elem in
var newAggregate = aggregate
newAggregate[elem.0] = elem.1
return newAggregate
}
You can extend Dictionary so that it takes a sequence of tuples as initial values:
extension Dictionary {
public init<S: SequenceType where S.Generator.Element == (Key, Value)>(_ seq: S) {
self.init()
for (k, v) in seq { self[k] = v }
}
}
and then do
let newDictionary = Dictionary(newTupleArray)

Correct way to access Multi-Dimensional Array with string indexes in Lua?

I'm trying to have a good access to multi-dimensional arrays with string indexes in Lua, here's basically what I'm trying to do:
rules =
{
{"S_RIGHT", "A_STOP", "S_RESULT"},
}
matrix = {}
for _,v in pairs(rules) do
if( matrix[ v[1] ] == nil ) then
matrix[ v[1] ] = {}
end
matrix[ v[1] ][ v[2] ] = v[3]
end
-- results in error ( attempt to index field 'S_NO' a nil value)
var = matrix["S_NO"]["S_RESULT"]
assert(var == nil, "Var should be nil")
A way to do it but quite verbose is:
var = matrix["S_NO"]
if var ~= nil then
var = var["S_RESULT"]
end
assert(var == nil, "Var should be nil")
Is there a way to make the first case to work ? ( less verbose )
Ok,
Found the answer.
If matrix is going to be read-only a correct approach would be:
local empty = {}
setmetatable(matrix, {__index=function() return empty end})
If I would like to allow writes and it's specifically two levels of tables, I could do:
setmetatable(matrix, {__index=function(t,k) local new={} rawset(t,k,new) return new end}
Hope this helps!

Resources