0

I have a new problem with R - I am currently teaching myself how to use it for my bachelor thesis in Psychology, so bear with me if my questions are really naive.

Right now I am trying to create a new variable based on an already existing one. The existing one has 4 different expressions: T1, T2, T3 and T4. They may look something like this:

subject       scenario
1             T1
2             T3
3             T3
4             T2
5             T2
6             T4

The new variable I am trying to create should give the following values: For T1 and T2the new variable should be personal and for T3and T4it should be impersonal. The output data should therefore look like this:

subject      scenario    personal force
1            T1          personal
2            T3          impersonal
3            T3          impersonal
4            T2          personal
5            T2          personal
6            T4          impersonal

What code can I create to do this? Any help would be greatly appreciated. Thanks!:)

  • TRY: pd %>% mutate(personal_force = ifelse(scenario %in% c('T1','T2'), 'personal', 'impersonal')) where 'pd' is your dataframe – Karthik S Nov 22 '20 at 13:16

2 Answers2

0

One option can be:

#Code
df$NewVar <- ifelse(df$scenario %in% c('T1','T2'),'personal','impersonal')

Another option with indexing (if you only want the new variable with the classes personal/impersonal):

#Code 2
df$NewVar <- 'impersonal'
df$NewVar[df$scenario %in% c('T1','T2')] <- 'personal'

The output in both cases:

df
  subject scenario     NewVar
1       1       T1   personal
2       2       T3 impersonal
3       3       T3 impersonal
4       4       T2   personal
5       5       T2   personal
6       6       T4 impersonal

It can be also done using dplyr with mutate() and passing the ifelse() but you will have to install the package and learn about its functions. As you are beginner in R you could start first with base R and then upgrade to dplyr style.

Duck
  • 39,058
  • 13
  • 42
  • 84
  • 1
    Thank you! Your first recommendation worked like a charm. – Carolin Schips Nov 22 '20 at 13:36
  • @CarolinSchips Great! Continue learning to master `R` :) and if you have any pitfall related to some project let me know. I use to teach customized R programming sessions to solve key issues. If you feel interested at any point of time let me know :) – Duck Nov 22 '20 at 13:38
0

Another way would be to use logical subsetting to create new column.

df$personal_force <- c('impersonal', 'personal')[df$scenario %in% c('T1', 'T2') + 1]
df

#  subject scenario personal_force
#1       1       T1       personal
#2       2       T3     impersonal
#3       3       T3     impersonal
#4       4       T2       personal
#5       5       T2       personal
#6       6       T4     impersonal
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213