[R] Replace values in a dataframe
Sarah Goslee
sarah.goslee at gmail.com
Wed Jun 17 19:44:32 CEST 2015
Hi Shane,
On Wed, Jun 17, 2015 at 1:31 PM, Shane Carey <careyshan at gmail.com> wrote:
> Hey all,
>
> I have a dataframe that consists of:
>
> structure(list(Color = c("5", "<4","5", "<5", "5"), Unit = c("Hazen",
> "Hazen",
> "Hazen", "Hazen", "Hazen")), .Names = c("Color", "Unit"), row.names =
> c("1:2",
> "1:3", "1:4", "1:5","1:6"), class = "data.frame")
Thanks for providing data.
>
> I need to find the <4 and have a new column with the result of 4 ÷ 2 = 2
>
> Similarly
>
> I need to find the <5 and have the new column with the result of 5 ÷ 2 = 2.5
Are "<4" and "<5" the only possible non-numeric values? If so, this is
an easy way to do it:
> mydata <- structure(list(Color = c("5", "<4","5", "<5", "5"), Unit = c("Hazen",
+ "Hazen",
+ "Hazen", "Hazen", "Hazen")), .Names = c("Color", "Unit"), row.names =
+ c("1:2",
+ "1:3", "1:4", "1:5","1:6"), class = "data.frame")
> mydata
Color Unit
1:2 5 Hazen
1:3 <4 Hazen
1:4 5 Hazen
1:5 <5 Hazen
1:6 5 Hazen
> mydata$NewColor <- ifelse(mydata$Color == "<4", 4/2, ifelse(mydata$Color == "<5", 5/2, as.numeric(mydata$Color)))
> mydata
Color Unit NewColor
1:2 5 Hazen 5.0
1:3 <4 Hazen 2.0
1:4 5 Hazen 5.0
1:5 <5 Hazen 2.5
1:6 5 Hazen 5.0
This will throw a warning message that you can safely ignore.
> All other numeric values would be added to the new column also to end up
> with:
>
> Color New value Unit 1:2 5 5 Hazen 1:3 <4 2 Hazen 1:4 5 5 Hazen 1:5 <5
> 2.5 Hazen 1:6 5 5 Hazen
Bonus points for providing data, demerits for posting in HTML so your
email got mangled.
Sarah
--
Sarah Goslee
http://www.functionaldiversity.org
More information about the R-help
mailing list