2

So I'm diving into yet another language (R), and need to be able to look at individual items in a dataframe(?). I've tried a number of ways to access this, but so far am confused by what R wants me to do to get this out. Current code:

empStatistics <- read.csv("C:/temp/empstats.csv", header = TRUE, row.names = NULL, encoding = "UTF-8", sep = ",", dec = ".", quote = "\"", comment.char = "") 
attach(empStatistics)
library(svDialogs)
Search_Item <- dlgInput("Enter a Category", "")$res
if (!length(Search_Item)) {
  cat("You didn't pick anything!?")
} else {
    Category <- empStatistics[Search_Item]
  }
Employee_Name <- dlgInput("Enter a Player", "")$res
if (!length(Employee_Name)) {
  cat("No Person Selected!\n")
} else {
  cat(empStatistics[Employee_Name, Search_Item])
}

and the sample of my csv file:

Name,Age,Salary,Department
Frank,25,40000,IT
Joe,24,40000,Sales
Mary,34,56000,HR
June,39,70000,CEO
Charles,60,120000,Janitor

From the languages I'm used to, I would have expected the brackets to work, but that obviously isn't the case here, so I tried looking for other solutions including separating each variable into its own brackets, trying to figure out how to use subset() (failed there, not sure it is applicable), tried to find out how to get the column and row indexes, and a few other things I'm not sure I can describe.

How can I enter values into variables, and then use that to get the individual pieces of data (ex, enter "Frank" for the name and "Age" for the search item and get back 25 or "June" for the name and "Department" for the search item to get back "CEO")?

NelsonGon
  • 13,015
  • 7
  • 27
  • 57
Tom A
  • 1,662
  • 2
  • 23
  • 41
  • 3
    Does this answer your question? [The difference between bracket \[ \] and double bracket \[\[ \]\] for accessing the elements of a list or dataframe](https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el) – NelsonGon May 05 '20 at 16:41
  • 1
    To get Frank and Age: `df1[df1=="Frank","Age"]`. Also look at `?`[` and `?subset` plus `?Extract` For June: `df1[df1=="June",c("Age","Department")]` – NelsonGon May 05 '20 at 16:44

1 Answers1

0

If you would like to access it like that, you can do:

Search_Item  <- "Salary"
Employee_Name <- "Frank"

empStatistics <- read.csv("empstats.csv",header = TRUE, row.names = 1)
empStatistics[Employee_Name,Search_Item]
[1] 40000

R doesn't have an Index for its data.frame. The other thing you can try is:

empStatistics <- read.csv("empstats.csv",header = TRUE)
empStatistics[match(Employee_Name,empStatistics$Name),Search_Item]
[1] 40000
StupidWolf
  • 45,075
  • 17
  • 40
  • 72