1

enter image description here

I do not know how to program in R at all, I only know python pandas. How to do the following in R:

  • my code has two variables, username and asignment
  • I want to filter my dataframe so that I only get the row that has name == username...
  • and then I only want the the column whose name matches the variable asignment.

Pictured is how I did it in Python pandas just to make it clear what I want. How do I do this in R?

smci
  • 32,567
  • 20
  • 113
  • 146
ai.jennetta
  • 1,076
  • 2
  • 10
  • 25

2 Answers2

3

If you only want the value you can use:

df$asgn1[df$name == username]

Or, using dplyr to get the column you can use filter and select

library(dplyr)
df %>%
  filter(name == username) %>%
  select(asgn1)
Bjørn Kallerud
  • 979
  • 8
  • 23
  • so the problem here is that i dont actually know that the value entered is asgn1. All i know is the variable assignment. How would I change the code to work if all i know is a variable? – ai.jennetta Jul 24 '19 at 23:52
  • @datasciencephl. If that is the ccase, it would be `df[[assignment]][df$name == username]` – akrun Jul 25 '19 at 01:43
0

You could do

df[df$name == username, assignment]
#[1] 80

Or you can also subset based on column position

df[df[, 1] == username, assignment]

In dplyr you could also use pull to get column name as vector

library(dplyr)
df %>%
  filter(name == username) %>%
  pull(assignment)

data

df <- data.frame(name = c("Jenna", "Alex", "Nick"), asgn1 = c(80, 90, 92), 
                 asgn2 = c(82, 92, 94), stringsAsFactors = FALSE)
username = "Jenna"
assignment = "asgn1"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213