0

I'm trying to add a new column to an existing dataframe. This column should contain id number, first letter of first name and first letter of last name. I've used the following code to add the column:

my_table%>% 
  unite(newID, c("id", "FirstName", "Surname"))

...and it shows the new column as a tibble, but not in the dataframe itself.

What am I missing? Going crazy here.

Thanks in advance,

mnist
  • 6,571
  • 1
  • 18
  • 41
MrsP
  • 3
  • 1
  • Welcome to SO! Please provide a [reproducible minimal example](https://stackoverflow.com/q/5963269/8107362) – mnist Oct 31 '19 at 22:34

1 Answers1

0

I think your problem is that you're not setting remove = FALSE in the unite call.

library(dplyr)

my_table %>%
  unite(
    'newID',
    id, FirstName, Surname,
    remove = FALSE
  )

However, that won't help you with your specification of only keeping the first letter of first & last name.
Just use mutate for this and specify exactly what you want to paste together:

library(dplyr)

my_table %>%
  mutate(
    newID = paste0(id, substr(FirstName,1,1), substr(Surname,1,1))
  )
alex_jwb90
  • 1,663
  • 1
  • 11
  • 20
  • Yes, that worked perfectly! Thank you! I just changed the "substr(Surname,1,1)" to "substr(Surname,2,2)" as I had a space before the Surname so the output was 1A B instead of 1AB. The only thing that confuses me is the fact it shows correctly in the console window, but it did not add a column to the actual table. I suppose I have to add it myself, perhaps using cbind? – MrsP Nov 02 '19 at 19:10
  • EDIT***got it, I wasn't assigning it to my_table, just added "my_table =" which solved it. Thanks again! – MrsP Nov 02 '19 at 19:45
  • Ah, good you solved it. To address your leading space, perhaps you would want to mutate that away, using `Surname = trimws(Surname)` – alex_jwb90 Nov 03 '19 at 23:16