###################################################

问题:给某一列赋值、分组、分类、因子化   18.4.24

如何把 data.frame 中的某一列,赋值、即分组分类,,

解决方案:

先 复制 要赋值的这一列,

iris1<- iris;  range(iris1$Sepal.Length)    #[1] 4.3  7.9 得到数据范围,为下面分段

方法一: 常规赋值,,可适用于被赋值列为 numeric、character 均可。为 numeric 时可用< > >= <= 等,character 时可用 == 方式。

iris1$Sepal.Length_fuzhi1 <- iris1$Sepal.Length;

str(iris1)

iris1$Sepal.Length_fuzhi1[iris1$Sepal.Length < 5] <- 1  #条件用 iris1$Sepal.Length 列,而不用新复制的列,是为了防止犯错    

iris1$Sepal.Length_fuzhi1[iris1$Sepal.Length >= 5 & iris1$Sepal.Length < 6] <- 2

iris1$Sepal.Length_fuzhi1[iris1$Sepal.Length >= 6 & iris1$Sepal.Length < 7] <- 3

iris1$Sepal.Length_fuzhi1[iris1$Sepal.Length >= 7] <- 4;

str(iris1)

  

方法二: 自定义函数去赋值,,用于被赋值列可以比较大小,如 numeric 型,

iris1<- iris
num_assign <- function(temp_df,col_name,clas,newname){ ##此函数为通用函数。。对可以比大小的列进行赋值的函数。
# temp_data 即要处理的数据框的名字,col_name为数据框中要处理的列名。
# clas为分组界限组成的向量。。newname为赋值后的新产生的列的列名。、。。。
temp_df[["temp1"]] = temp_df[["temp"]] <- temp_df[[col_name]];
CI <- rep("a",length(clas)+1); #CI 用来显示 原来值与新赋的值 之间对应关系。
for(i in 1:length(clas)) {
if(i == 1){ #得到第一个区间
temp_df[["temp"]][temp_df[["temp1"]] < clas[i]] <- i
CI[i] <- paste("<",clas[i])
}else if(i>1 & i<length(clas)){ ###得到 第 2 到第 n-1 个区间
temp_df[["temp"]][temp_df[["temp1"]] >= clas[i-1] & temp_df[["temp1"]] < clas[i]] <- i
CI[i] <- paste0(clas[i-1],"<=","x","<",clas[i])
}else{ #得到第n个和n+1个区间
temp_df[["temp"]][temp_df[["temp1"]] >= clas[i-1] & temp_df[["temp1"]] < clas[i]] <- i
CI[i] <- paste0(clas[i-1],"<=","x","<",clas[i])
temp_df[["temp"]][temp_df[["temp1"]] >= clas[i]] <- i+1
CI[i+1] <- paste0(">=",clas[i])
}
}
temp_df <- subset(temp_df,select = -temp1) #删除临时列temp1
names(temp_df)[names(temp_df)=="temp"] = newname #将新的列名赋给临时列名。
assign_explain <- data.frame(num = 1:(length(clas)+1),CI = CI); assign_explain
result <- list(temp_df=temp_df,assign_explain=assign_explain)
return(result)
}
#应用上面函数:
iris1 <- num_assign(iris1,"Sepal.Length",c(5,6,7),"fuzhii_")[[1]]
assign_explain_age <- num_assign(iris1,"Sepal.Length",c(5,6,7),"fuzhii_")[[2]]; assign_explain_age

  方法二: 自定义函数去赋值,,用于被赋值列不能比较大小,如 character 型,

chr_assign <- function(temp_df,col_name,newname){    ##此函数为通用函数。。对不用比大小的列进行赋值的函数。
# temp_data 即要处理的数据框的名字,col_name为数据框中要处理的列名。
# 。newname为赋值后的新产生的列的列名。、。。。
temp_df[["temp1"]] = temp_df[["temp"]] <- as.character(temp_df[[col_name]])
clas <- as.character(unique(temp_df[["temp1"]]))
CI <- rep("a",length(clas)) #用来生成原值 和 所赋值的对应关系
for(i in 1:length(clas)) {
temp_df[["temp"]][temp_df[["temp1"]] == clas[i]] <- i
CI[i] <- clas[i]
}
temp_df <- subset(temp_df,select = -temp1) #删除临时列temp1
names(temp_df)[names(temp_df)=="temp"] = newname #将新的列名赋给临时列名。
assign_explain <- data.frame(num = 1:(length(clas)),CI = CI) #生成赋值与相应区间的对应关系变量
result <- list(temp_df=temp_df,assign_explain=assign_explain)
return(result)
}
#应用上面函数:
iris1 <- chr_assign(iris1,"Species","leibie")[[1]]; str(iris1) assign_explain_age <- chr_assign(iris1,"Species","leibie")[[2]]; assign_explain_age

  

讨论扩展:同上的思路,可以扩展用于分类变量,不限于比较大小的 numeric 型。另外亦可将iris1 作为中间数据框,用 iris1 <- new_data.frame .

扩展1:

筛选条件 iris1$Sepal.Length < 5 返回一个逻辑向量,长度为 iris1 的长度150,这在将来赋值的时候 iris1$Sepal.Length_fuzhi1[iris1$Sepal.Length < 5] <- 1 ,会不会计算 150 次,是TRUE了,赋值,,是 FALSE 了,不赋值。

改换条件方式为:which(iris1$Sepal.Length < 5) 返回一个位置向量,长度为满足筛选条件的行数22,这在将来赋值时候,会不会更有效率。。??。。

 扩展2:扩展版方法二:一个例子。。可 用于 numeric character 型。。

#将可以比较大小的列,分组、赋值
if(num_or_char == "num")
{
temp_df <- iris1
temp_df$temp1 = temp_df$temp <- temp_df$Sepal.Length
clas <- c(5,6,7); clas ### seq(from=, to=, by=)
CI <- rep("a",length(clas)+1); #用来生成赋值后的区间 和 所赋值的对应关系
for(i in 1:length(clas)) {
if(i == 1){ #得到第一个区间
temp_df$temp[temp_df$temp1 < clas[i]] <- i ### 即满足 <5
CI[i] <- paste("<",clas[i])
}else if(i>1 & i<length(clas)){ ###得到 第 2 到第 n-1 个区间
temp_df$temp[temp_df$temp1 >= clas[i-1] & temp_df$temp1 < clas[i]] <- i ### 即满足 5 =< x < 6
CI[i] <- paste0(clas[i-1],"<=","x","<",clas[i])
}else{ #得到第n个和n+1个区间
temp_df$temp[temp_df$temp1 >= clas[i-1] & temp_df$temp1 < clas[i]] <- i ### 即满足 6 =< x < 7
CI[i] <- paste0(clas[i-1],"<=","x","<",clas[i])
temp_df$temp[temp_df$temp1 >= clas[i]] <- i+1 ### 即满足 x >= 7
CI[i+1] <- paste0(">",clas[i])
}
}
temp_df <- subset(temp_df,select = -temp1) #删除临时列temp1
names(temp_df)[names(temp_df)=="temp"] = "newname"
assign_explain <- data.frame(num = 1:(length(clas)+1),CI = CI); assign_explain #生成赋值与相应区间的对应关系变量
} #将不能够比较大小的列,分组、赋值
if(num_or_char == "char"){
temp_df <- iris1
temp_df$temp1 = temp_df$temp <- as.character(temp_df$Species)
clas <- as.character(unique(temp_df$temp));clas
CI <- rep("a",length(clas)); #用来生成原值 和 所赋值的对应关系
for(i in 1:length(clas)) {
temp_df$temp[temp_df$temp1 == clas[i]] <- i
CI[i] <- clas[i]
}
temp_df <- subset(temp_df,select = -temp1) #删除临时列temp1
names(temp_df)[names(temp_df)=="temp"] = "newname" #将临时列 temp 重命名为设置的列名
assign_explain <- data.frame(num = 1:length(clas),CI = CI); assign_explain #生成赋值与相应区间的对应关系变量
}

#实现按照两列分别分组,且组合后的各种情况分组、赋值

temp_df <- iris1
temp_df$temp1 = temp_df$temp <- temp_df$Sepal.Length
clas <- c(5,6,7); clas ### seq(from=, to=, by=)
clas2 <- as.character(unique(temp_df$Species));clas2
newname = "SL_Species_"
CI <- rep("a",length(clas)*length(clas2));
num <- rep(1,length(clas)*length(clas2));
k = 1
for(i in 1:length(clas)) {
for(j in 1:length(clas2)){
# num[2*(i-1)+j] <- 10*j+i
if(i == 1){ #得到第一个区间
temp_df$temp[temp_df$temp1 < clas[i] & temp_df$Species == clas2[j]] <- 10*j+i
num[k] <- 10*j+i
CI[k] <- paste0(clas2[j],"且 Sepal.Length","<",clas[i])
}else if(i>1 & i<length(clas)){ ###得到 第 2 到第 n-1 个区间
temp_df$temp[temp_df$temp1 >= clas[i-1] & temp_df$temp1 < clas[i] & temp_df$Species == clas2[j]] <- 10*j+i
num[k] <- 10*j+i
CI[k] <- paste0(clas2[j],"且 Sepal.Length",clas[i-1],"<=","x","<",clas[i])
}else{ #得到第n个和n+1个区间
temp_df$temp[temp_df$temp1 >= clas[i-1] & temp_df$temp1 < clas[i] & temp_df$Species == clas2[j]] <- 10*j+i
num[k] <- 10*j+i
CI[k] <- paste0(clas2[j],"且 Sepal.Length",clas[i-1],"<=","x","<",clas[i])
k <- k+1
temp_df$temp[temp_df$temp1 >= clas[i] & temp_df$Species == clas2[j]] <- 10*j+(i+1)
num[k] <- 10*j+(i+1)
CI[k] <- paste0(clas2[j],"且 Sepal.Length",">=",clas[i])
}
k <- k+1
}
}
temp_df <- subset(temp_df,select = -temp1);str(temp_df) #删除临时列temp1
names(temp_df)[names(temp_df)=="temp"] = newname
assign_explain <- data.frame(num=num, CI=CI); assign_explain

   

另请参阅:for 循环,,自定义函数,,

R: 给 dataframe 的某列赋值、分组、因子化的更多相关文章

  1. pandas DataFrame行或列的删除方法

    pandas DataFrame的增删查改总结系列文章: pandas DaFrame的创建方法 pandas DataFrame的查询方法 pandas DataFrame行或列的删除方法 pand ...

  2. Spark SQL DataFrame新增一列的四种方法

    方法一:利用createDataFrame方法,新增列的过程包含在构建rdd和schema中 方法二:利用withColumn方法,新增列的过程包含在udf函数中 方法三:利用SQL代码,新增列的过程 ...

  3. 更改 pandas dataframe 中两列的位置

    更改 pandas dataframe 中两列的位置: 把其中的某列移到第一列的位置. 原来的 df 是: df = pd.read_csv('I:/Papers/consumer/codeandpa ...

  4. Spark 将DataFrame所有的列类型改为double

    Spark 将DataFrame所有的列类型改为double 1.单列转化方法 2.循环转变 3.通过:_* 1.单列转化方法 import org.apache.spark.sql.types._ ...

  5. R语法学习 第十二篇:因子

    因子(factor)是R语言中比较特殊的一个类型, 它是一个用于存储类别的类型,因子的行为有时像字符串,有时像整数.因子也是一个向量,每个元素都是字符类型.因子具有因子水平(Levels),用于限制因 ...

  6. pandas应用之分组因子暴露和分位数分析

    pandas应用之分组因子暴露和分位数分析 首先感谢原书作者Mes McKinney和batteryhp网友的博文, 俺在此基础上继续探索python的神奇功能. 用A股的实际数据, 以书里的代码为蓝 ...

  7. pandas 按照列A分组,将同一组的列B求和,生成新的Dataframe

    对于pandas中的Dataframe,如果需要按照列A进行分组,将同一组的列B求和,可以通过下述操作完成: df = df.groupby(by=['column_A'])['column_B']. ...

  8. [R] R dataframe 中对列使用sort或者order的注意

    存在这样的需求: 针对每列的值, 对列进行排序. 这样处理过数据后, 在excel中对数据作图时, 使数据呈现有序. R中sort数据的时候, 如果数据中存在字符串, R会将数据转化为characte ...

  9. R语言dataframe的常用操作总结

    前言:近段时间学习R语言用到最多的数据格式就是data.frame,现对data.frame常用操作进行总结,其中函数大部分来自dplyr包,该包由Hadley Wickham所作,主要用于数据的清洗 ...

随机推荐

  1. cscope配置和使用

    , cscope安装 软件下载:http://sourceforge.net/project/showfiles.php?group_id=4664 软件安装: ./configure --with- ...

  2. UVA - 242 Stamps and Envelope Size (完全背包+bitset)

    题意:给你一些邮票面值的集合,让你选择其中一个集合,使得“能用不超过n枚集合中的邮票凑成的面值集合S中从1开始的最大连续面值”(即mex(S)-1)最大.如果有多解,输出集合大小最小的一个:如果仍有多 ...

  3. Long Jumps(二分查找lower_bound()函数的运用)

    Valery is a PE teacher at a school in Berland. Soon the students are going to take a test in long ju ...

  4. oracle获得当前时间,精确到毫秒并指定精确位数

    oracle获得当前时间的,精确到毫秒   可以指定精确豪秒的位数 select to_char(systimestamp, 'yyyymmdd hh24:mi:ss.ff ') from dual; ...

  5. [转] 如何用BSP树生成游戏地图

    作者:Timothy Hely 当用对象随机填充某个区域如地下城中的房间时,你可能会遇到的问题是太过随机,导致分布疏密不均或混乱.在本教程中,我将告诉大家如何使用二进制空间划分法(游戏邦注:即Bina ...

  6. div+css制作带箭头提示框效果图(原创文章)

    一直都在看站友们的作品,今天也来给大家分享一个小的效果,第一次发还有点小紧张呢,语言表达能力不是很好,还请见谅…^ 先来个简单点的吧,上效果图 刚开始在网上看到效果图的时候感觉好神奇,当我试着写出来的 ...

  7. 机器学习:PCA(实例:MNIST数据集)

    一.数据 获取数据 import numpy as np from sklearn.datasets import fetch_mldata mnist = fetch_mldata("MN ...

  8. WebDriver测试web中遇到的弹出框或不确定的页面

    我自己是用try catch解决的,不知道其他人的解决方法?如有,可以留言

  9. mongodb collection method

    https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/ db.coll_test.getIndexes()# ...

  10. 为什么每个浏览器都有Mozilla字样

    你是否好奇标识浏览器身份的User-Agent,为什么每个浏览器都有Mozilla字样?Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 ( ...