0

Let I have such a data frame(df):

df:

header1   header2
------    -------
45        76
54        89
-         12
45        32
12        34
-         5
45        34
65        54

I want to get such a dataframe

header1   header2
------    -------
45        76
54        89
-         -
45        32
12        34
-         -
45        34
65        54

Namely I want to replace values in header2 columsn with "-", which rows of column header1 have "-" values.

How can I do that in R? I will be very glad for any help. Thanks a lot.

mtoto
  • 23,919
  • 4
  • 58
  • 71
oercim
  • 1,808
  • 2
  • 17
  • 34
  • Could you please add the output of `str(df)` so we can see the structure of your data frame? That will likely affect the code used to get your desired result. – josliber Mar 03 '16 at 18:40

2 Answers2

3

If both columns if your df are character vectors, you could do:

# You can convert your columns to character with
df[,1:2] <- lapply(df[,1:2], as.character) 

df$header2[df$header1 == "-"] <- "-" # Replace values
> df
#  header1 header2
#1      45      76
#2      54      89
#3       -       -
#4      45      32
#5      12      34
#6       -       -
#7      45      34
#8      65      54
mtoto
  • 23,919
  • 4
  • 58
  • 71
1

Traditionally, I would suggest making use of dplyr as it produces beautify readable workflow when working on data frames.

set.seed(1)
dta <- data.frame(colA = c(12,22,34,"-",23,"-"),
                  colB = round(runif(n = 6, min = 1, max = 100),0))

Vectorize(require)(package = c("dplyr", "magrittr"),
                                     character.only = TRUE)

dta %<>%
    mutate(colB = ifelse(colA == "-", "-", colA))

This would give you the following results:

> head(dta)
  colA colB
1   12    2
2   22    3
3   34    5
4    -    -
5   23    4
6    -    -

Side notes

This is very flexible mechanism but if you presume that the column classes may be of relevance you may simply choose to run mutate_each(funs(as.character)) before applying any other transformations.

Konrad
  • 17,740
  • 16
  • 106
  • 167