请问添加列,该列包含整数列的绑定值。

添加列,该列包含整数列的绑定值。

我有一个包含几个列的dataframe,其中一个列是秩,一个介于1到20之间的整数。我想创建另一个列,它包含一个bin值,比如“1-4”、“5-10”、“11-15”、“16-20”。

做这件事最有效的方法是什么?

我拥有的数据框架如下(.csv格式):

rank,name,info1,steve,red3,joe,blue6,john,green3,liz,yellow15,jon,pink

我想在dataframe中添加另一列,所以如下所示:

rank,name,info,binValue1,steve,red,"1-4"3,joe,blue,"1-4"6,john,green, "5-10"3,liz,yellow,"1-4"15,jon,pink,"11-15"

我现在这样做是不起作用的,因为我想保持data.framework不变,如果df$放的值在给定的范围内,只需添加另一列即可。谢谢。


小唯快跑啊
浏览 509回答 3
3回答

慕莱坞森

看见?cut并指定breaks(也许labels).x$bins <- cut(x$rank, breaks=c(0,4,10,15), labels=c("1-4","5-10","10-15"))x#&nbsp; &nbsp;rank&nbsp; name&nbsp; &nbsp;info&nbsp; bins# 1&nbsp; &nbsp; 1 steve&nbsp; &nbsp; red&nbsp; &nbsp;1-4# 2&nbsp; &nbsp; 3&nbsp; &nbsp;joe&nbsp; &nbsp;blue&nbsp; &nbsp;1-4# 3&nbsp; &nbsp; 6&nbsp; john&nbsp; green&nbsp; 5-10# 4&nbsp; &nbsp; 3&nbsp; &nbsp;liz yellow&nbsp; &nbsp;1-4# 5&nbsp; &nbsp;15&nbsp; &nbsp;jon&nbsp; &nbsp;pink 10-15&nbsp;

万千封印

dat <- "rank,name,info1,steve,red3,joe,blue6,john,green3,liz,yellow15,jon,pink"x <- read.table(textConnection(dat), header=TRUE, sep=",", stringsAsFactors=FALSE)x$bins <- cut(x$rank, breaks=seq(0, 20, 5), labels=c("1-5", "6-10", "11-15", "16-20"))x&nbsp; rank&nbsp; name&nbsp; &nbsp;info&nbsp; bins1&nbsp; &nbsp; 1 steve&nbsp; &nbsp; red&nbsp; &nbsp;1-52&nbsp; &nbsp; 3&nbsp; &nbsp;joe&nbsp; &nbsp;blue&nbsp; &nbsp;1-53&nbsp; &nbsp; 6&nbsp; john&nbsp; green&nbsp; 6-104&nbsp; &nbsp; 3&nbsp; &nbsp;liz yellow&nbsp; &nbsp;1-55&nbsp; &nbsp;15&nbsp; &nbsp;jon&nbsp; &nbsp;pink 11-15

慕姐8265434

我们可以用smart_cut从包装cutr :# devtools::install_github("moodymudskipper/cutr")library(cutr)使用@Andrie的样本数据:x$bins <- smart_cut(x$rank,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c(1,5,11,16),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; labels = ~paste0(.y[1],'-',.y[2]-1),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; simplify = FALSE)# rank&nbsp; name&nbsp; &nbsp;info&nbsp; bins# 1&nbsp; &nbsp; 1 steve&nbsp; &nbsp; red&nbsp; &nbsp;1-4# 2&nbsp; &nbsp; 3&nbsp; &nbsp;joe&nbsp; &nbsp;blue&nbsp; &nbsp;1-4# 3&nbsp; &nbsp; 6&nbsp; john&nbsp; green&nbsp; 5-10# 4&nbsp; &nbsp; 3&nbsp; &nbsp;liz yellow&nbsp; &nbsp;1-4# 5&nbsp; &nbsp;15&nbsp; &nbsp;jon&nbsp; &nbsp;pink 11-15更多关于切割和智能切割
打开App,查看更多内容
随时随地看视频慕课网APP