0

I have data that looks like the following:

pig<-data.frame(a=c("","","","","","Type1"),b=c("T1 NR","T2 NR","T2","T3","T3","Type1"))
print(pig)
  a      b
       T1 NR
       T2 NR
       T2
       T3
       T3
Type1  Type 1

Where a will sometimes be blank, but b always has information that corresponds to the missing information in a. I am looking for two things. First, where "NR" is present in b, I want "NR" to appear in a. Second, where "NR" is not present in b and a is blank, I would like some other string to appear in such as "DKT" to get something like the following:

cow<-data.frame(a=c("NR","NR","DKT","DKT","DKT","Type1"),b=c("T1 NR","T2 NR","T2","T3","T3","Type1"))
print(cow)
 a     b
NR   T1 NR
NR   T2 NR
DKT   T2
DKT   T3
DKT   T3
Type1 Type1

Thanks!

2
  • 1
    Try library(tidyverse);pig %>% mutate(a = case_when(str_detect(b, "NR") ~"NR", a == "" ~ "DKT", TRUE ~ as.character(a))) Commented Jan 22, 2018 at 18:37
  • 2
    Using ifelse ifelse(pig$a == "", ifelse(grepl("NR", pig$b), "NR", "DKT"), as.character(pig$a)) Commented Jan 22, 2018 at 18:39

1 Answer 1

1

You can assign using row/column subsetting with a data.frame.

# You're doing string editing, so let's avoid factors from the start
pig <- data.frame(
  a = c("","","","","","Type1"),
  b = c("T1 NR","T2 NR","T2","T3","T3","Type1"),
  stringsAsFactors = FALSE
)

# The actual solution
has_nr <- grepl("NR", pig$b)
pig[has_nr, "a"] <- "NR"
pig[!has_nr & pig$a == "", "a"] <- "DKT"
Sign up to request clarification or add additional context in comments.

6 Comments

I get an error when applying the last line: Error in chatToDate(x): character string is not in a standard unambiguous format I think it might be an issue with the blanks, which could be a different question. However, any thoughts?
What's the class of the a column in your dataset? Is it a Date vector?
It is class character
I'm guessing the error actually says charToDate instead of chatToDate. If so, somewhere in your code you're attempting to convert a character value to a Date, but it's unclear how to interpret it. Even if you're not calling as.Date() yourself, you might be assigning a value into a Date vector.
You are correct, that was a typo. I convert another column to a date, but not the one I am working on. What would be the best way to go about fixing the issue?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.