[英]Changing value based on a condition in r
I have the following dataframe 我有以下数据框
head(data)
Date Avg.Join.Delay Min.Join.Dely Max.Join.Dely ACCOUNT STB_TYPE MARKET
1 6/5/2015 500 500 500 3036831961 IPH8005 Denver
2 6/5/2015 500 500 500 3038416736 IPH8005 Denver
3 6/5/2015 500 500 500 4802192190 IPH8005 Phoenix
4 6/5/2015 500 500 500 4802193088 IPH8005 Phoenix
5 6/5/2015 500 500 500 4802795632 IPH8005 Phoenix
6 6/5/2015 500 500 500 4803611713 IPH8005 Phoenix
I want to change the Account number to a City/State (303 = Colorado), but I am not sure what is the correct syntax of this kind of script. 我想将帐号更改为城市/州(303 =科罗拉多州),但是我不确定这种脚本的正确语法是什么。
I tried data$ACCOUNT[data$ACCOUNT == "303%"] <- "Colorado"
but it doesn't change the value. 我尝试了data$ACCOUNT[data$ACCOUNT == "303%"] <- "Colorado"
但它不会更改值。 Any idea how to do it in a way that it will change all the values that begin with xxx
? 知道如何以某种方式更改所有以xxx
开头的值的方式吗?
You can try using substr
to extract the first 3 characters 您可以尝试使用substr
提取前3个字符
data$ACCOUNT[substr(data$ACCOUNT,1,3)=='303'] <- 'Colorado'
Or use sub
或使用sub
data$ACCOUNT[sub('(.{3}).*', '\\1',data$ACCOUNT)=='303'] <- 'Colorado'
Or grep
或grep
data$ACCOUNT[grepl('^303', data$ACCOUNT)] <- 'Colorado'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.