当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


R语言 droplevels()用法及代码示例


R 编程中的 droplevels() 函数用于从因子中删除未使用的级别。

用法:
# For vector object
droplevels(x, exclude = if(anyNA(levels(x))) NULL else NA, …)

# 对于 DataFrame 对象
droplevels(x,除了,排除)

Parameter values:
x表示必须从中删除未使用级别的对象
排除表示即使存在也应排除的因子水平
除了表示不应从中删除级别的列的索引

范例1:




# Defining vector
x <- c(1, 3, 4, 8, 1, 5, 4, 4, 5, 6)
  
# Defining factor object for vector
f <- factor(x)
  
# Print factor object
cat("Factor object before deleting value:\n")
print(f)
cat("\n")
  
# Delete value at index 2
f <- f[-2]
  
# Print factor object
cat("Factor object after deleting value:\n")
print(f)
cat("\n")
  
cat("After dropping unused level:\n")
new_f <- droplevels(f)
print(new_f)

输出:

Factor object before deleting value:
 [1] 1 3 4 8 1 5 4 4 5 6
Levels:1 3 4 5 6 8

Factor object after deleting value:
[1] 1 4 8 1 5 4 4 5 6
Levels:1 3 4 5 6 8

After dropping unused level:
[1] 1 4 8 1 5 4 4 5 6
Levels:1 4 5 6 8

范例2:


# Defining columns
x <- factor(c(7, 3, 3, 7, 5, 5, 1))
y <- factor(c(1, 1, 1, 4, 4, 4, 2))
z <- c(1, 5, 3, 2, 9, 4, 7)
  
# Defining data frame
df <- data.frame(x, y, z)
df <- df[1:6, ]
  
# Print structure of data frame
str(df)
cat("\n")
  
# Drop levels from data frame
df_drop <- droplevels(df)
  
# Print structure of new data frame
str(df_drop)

输出:

'data.frame':  6 obs. of  3 variables:
 $ x:Factor w/ 4 levels "1", "3", "5", "7":4 2 2 4 3 3
 $ y:Factor w/ 3 levels "1", "2", "4":1 1 1 3 3 3
 $ z:num  1 5 3 2 9 4
 
 'data.frame':  6 obs. of  3 variables:
 $ x:Factor w/ 3 levels "3", "5", "7":3 1 1 3 2 2
 $ y:Factor w/ 2 levels "1", "4":1 1 1 2 2 2
 $ z:num  1 5 3 2 9 4



相关用法


注:本文由纯净天空筛选整理自utkarsh_kumar大神的英文原创作品 Removing Levels from a Factor in R Programming – droplevels() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。