R语言:给数据帧中某列长度小于4的值,全部在前面以0补齐
1.生成数据帧data
data <- data.frame(
gender = c("Male", "Male","Female"),
height = c(152, 171.5, 165),
weight = c(81,93, 78),
SPEED =c(1242,38,2622)
)
运行的结果为:
data
gender height weight SPEED
1 Male 152.0 81 1242
2 Male 171.5 93 38
3 Female 165.0 78 2622
2.自定义补齐函数
若长度小于4,在记录前面以0补齐new.function <- function(x){
while(nchar(x)<4){
temp <- paste(0,x)
x <- temp
x <- gsub(" ","",x)
}
return(x)
}
3.执行补齐,并且替换原数据帧
data$SPEED <-lapply(data$SPEED,new.function)
data
最终运行
data
gender height weight SPEED
1 Male 152.0 81 1242
2 Male 171.5 93 0038
3 Female 165.0 78 2622
data$SPEED[which(nchar(data$SPEED)<4)] <-1000 #这个是把长度小于4的,全部替换为1000.在此记录一下
热门评论
鄙视楼主,抄人家的也不写明出处。