-2

I want to create a new column in my dataframe such that it is formed by the first element (or 2 elements) of elements in another column in the same dataframe. E.g.

   columnA
1   "1234"
2   "9876"
3   "4567"

Turns into:

   columnA    columnB
1   "1234"       "12"
2   "9876"       "98"
3   "4567"       "45"

I tried with the dplyr library like this:

dataframe %>%
    mutate( columnB = columnA[1:2] )

But this is trying to retrieve the first two rows.

If anyone knows anyway to do this fast (preferably with dplyr library), I would appreciate it a lot. Thanks in advance.

Miguel Wang
  • 183
  • 1
  • 12

1 Answers1

1
df <- data.frame(columnA=c("1234","9876","4567"))
df$columnB <- substr(df$columnA,1,2)           
 #   columnA columnB
 # 1    1234      12
 # 2    9876      98
 # 3    4567      45 

If you want to use dplyr:

df <- df %>% mutate(columnB = substr(columnA,1,2))
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167