user3008387
user3008387

Reputation: 7

How to use a variable to specify a row of data in r

In r how can I select a data row by referencing the name of the employee : ALEX ,BRAD or JOHN with a variable?

From the code below I get:

missing value where TRUE/FALSE needed.
emp1["ALEX","mon"] 
[1] NA

csv example-

*  X.name mon tue wed thu fri
1   ALEX  98  95  73  88  18
2   BRAD  66  25  72   8  32
3   JOHN  22  41  78  43  36

    emp1 <- read.csv("C:/Database/data/emp1.csv",as.is=TRUE)
    emp2 <- read.csv("C:/Database/data/emp2.csv",as.is=TRUE)
    employeename<-"ALEX"
        if (emp1[employeename,"mon"] > emp2["2","mon"] & emp1["2","mon"]> emp2["3","mon"]) result<- "SUCCESS" else 

    result<-"fail"
    print (result)

Upvotes: 0

Views: 67

Answers (2)

Rich Scriven
Rich Scriven

Reputation: 99371

In addition to specifying the column, you can change the rownames and delete the first column, enabling you to call the row and column as you were previously calling it.

> rownames(emp1) <- emp1$X.name
> emp1 <- emp1[,-1]
> emp1["ALEX", "mon"]
## [1] 98

Upvotes: 2

Sven Hohenstein
Sven Hohenstein

Reputation: 81743

You have to specify the column, in this case X.name:

emp1[emp1$X.name == "ALEX", "mon"]

or

employeename <- "ALEX"
emp1[emp1$X.name == employeename, "mon"]

Upvotes: 1

Related Questions