yyyrsh yyyrsh - 10 months ago 30
R Question

Looping in R over variable in dataframe to get connected indexed variable

I want to write a loop to index the dataframe to choose a value based on input of A.
I have a dataframe:

A B
1234 2017-01-01
1235 2017-01-02
1256 2017-02-03


My Code:

fun <- function(input) {
for ( i in dataframe$A)
if (i == input)
print(dataframe$B[A])

fun(1234)
> 2017-01-01


So, I what I want is when my input is A, how do I get B returned (that is connected to A) ?

Answer Source

In R, it's usually not necessary to use for loops. There are more elegant functions built into the language to help you subset data. This will give you the result you want.

dataframe$B[dataframe$A == input]

And if you want to use it as a function, you can do this.

fun <- function(input)
{
    dataframe$B[dataframe$A == input]
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download