0

I hope this is the right place to ask my question: I want to replace longer male/female strings in the sex-column of my data.frame with just 'm'/'f'. How to build a wildcard-function stating "if string starts with m/f, set its values to m/f"?

Possible data:

df <- data.frame(list(A=c("fem","mal"), B=c(12, 17)))

Thank you so much

slamballais
  • 3,161
  • 3
  • 18
  • 29
Mac
  • 183
  • 1
  • 13
  • 1
    Please have a look at this: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Sotos Feb 16 '16 at 09:30
  • 1
    `dat$sex <- substr(dat$sex, 1, 1)`? – Axeman Feb 16 '16 at 09:33
  • if (df$A=="fem") df$A=="f" – CuriousBeing Feb 16 '16 at 09:36
  • many ways of doing it: `substring(x, 1, 1)` or use packages like `stringr` or `stringi` – Sotos Feb 16 '16 at 09:36
  • Thx! substr is perfect :) Where can I find basic guidelines for data.frame editing? I will encounter several more questions, like how to change "," into "." in one column of my dataframe.. – Mac Feb 16 '16 at 09:38
  • If you are importing data into R, checking the arguments of the importing function might save lots of time. –  Feb 16 '16 at 09:44
  • The import-code is more than 200 lines strong. I first use a basic import-script from my panel provider to get all the labels and stuff. In this complicated case, I think, it's best that I adjust my data after this step. – Mac Feb 17 '16 at 13:00

1 Answers1

1
df$A <- substring(df$A, 1, 1)
df
#   A  B
# 1 f 12
# 2 m 17
Sotos
  • 51,121
  • 6
  • 32
  • 66
  • I guess the problem is wider than th OP is currently showing. If you have other string than "fem" and "mal", it will fail. –  Feb 16 '16 at 09:42
  • Any other string that does not start with letters "m" or "f" you mean – Sotos Feb 16 '16 at 09:45
  • 1
    In fact I had wider strings (in another language) and the code worked as to reduce the string to its initial letter. Which I was looking for :) – Mac Feb 16 '16 at 09:45
  • @Mac Better to be more specific when asking a question, thank you. –  Feb 16 '16 at 09:46
  • @Mac, your question got a bit unclear when you stated your `if` statement. It can be interpreted as "there are also strings that do not begin with m or f" – Sotos Feb 16 '16 at 09:48
  • 1
    Ah ok. I only had those two strings (removed all NA in advance), so the solutions works great for me. – Mac Feb 16 '16 at 09:53