I want to create a new column to indicate the fuel type base on the previous fuel data, but I have no idea how to do that. Pleas help! Thanks
-
3add a reproducible example or a dataset we can use to help you. – MLavoie Dec 30 '15 at 22:02
-
2Please consider reading up on [ask] and how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Heroka Dec 30 '15 at 22:12
1 Answers
First, please take a look at the resources provided in the comments above on how to ask good questions here. It is sometimes a pain to set up a good question, but it really goes a long way towards getting your question answered quickly and effectively.
That aside, here's a stab at what I think you are asking for.
First, let's create a simple, reproducible data set (i.e. anybody can run this code to create the same data set, which means we're all starting from the same point):
df <- data.frame( fuel12 = c(100,0,0,100,0)
, fuel34 = c(0,100,0,100,0)
, fuel56 = c(0,0,100,0,0)
)
# fuel12 fuel34 fuel56
# 1 100 0 0
# 2 0 100 0
# 3 0 0 100
# 4 100 100 0
# 5 0 0 0
Next, we'll use apply
to look for any non-zero values within the columns of df
. If there are no non-zero values, then the column will say None
. I'm not sure if multiple non-zero columns is a possibility, but just in case we'll have all non-zero columns listed and delimited with a comma (e.g. fuel12,fuel34
).
df$which_fuel <- apply(df, 1, function(x) { ifelse(sum(x)==0
, "None"
, paste(names(df)[x > 0], collapse=",")
)})
df
# fuel12 fuel34 fuel56 which_fuel
# 1 100 0 0 fuel12
# 2 0 100 0 fuel34
# 3 0 0 100 fuel56
# 4 100 100 0 fuel12,fuel34
# 5 0 0 0 None
Is this what you were looking for?

- 338
- 3
- 9
-
Yes, that is exactly what I am looking for. I really appreciate for that! Also, I will take a look about how to ask question, thank you for the advise! – zihan meng Dec 31 '15 at 01:18