数据框为数字类别

时间:2017-03-18 21:15:07

标签: r

我有一个数据,下面给出了 // JavaScript source code var friends = require('./../controllers/friends.js'); module.exports = function(app) {...}

数据:

dput

数据是法语,基本上,它是从0到10,从10到20的类别,依此类推。我需要用数字替换第二列,例如,0×10厘米我需要分配到1×10×20厘米 - 到2,依此类推,如何根据R中的类别自动替换数值?

在新表中,我需要将第2列替换为类别级别的dput(data) structure(c(12L, 2L, 14L, 2L, 2L, 12L, 14L, 13L, 14L, 12L), .Label = c("0 Ã 10 cm", "10 Ã 20 cm", "100 Ã 110 cm", "110 Ã 120 cm", "120 Ã 130 cm", "130 Ã 140 cm", "140 Ã 150 cm", "150 Ã 160 cm", "160 Ã 170 cm", "170 Ã 180 cm", "180 Ã 190 cm", "20 Ã 30 cm", "30 Ã 40 cm", "40 Ã 50 cm", "50 Ã 60 cm", "60 Ã 70 cm", "70 Ã 80 cm", "80 Ã 90 cm", "90 Ã 100 cm", "N/A"), class = "factor") ,第2列的值将如下所示:

A

1 个答案:

答案 0 :(得分:1)

首先,您必须整理数据以清理结构。我是在数据部分做到的。然后将第一列转换为因子,然后转换为数字,以获取类别级别,并将其分配给第2列。

df[, 2] <- as.numeric( factor( df[[1]]) )

#    X1 X2    X3
# 1  20  2 30 cm
# 2  10  1 20 cm
# 3  40  4 50 cm
# 4  10  1 20 cm
# 5  10  1 20 cm
# 6  20  2 30 cm
# 7  40  4 50 cm
# 8  30  3 40 cm
# 9  40  4 50 cm
# 10 20  2 30 cm

数据:

df <- structure(c(12L, 2L, 14L, 2L, 2L, 12L, 14L, 13L, 14L, 12L),
                .Label = c("0 Ã  10 cm", "10 Ã  20 cm", "100 Ã  110 cm", "110 Ã  120 cm", "120 Ã  130 cm", 
                           "130 Ã  140 cm", "140 Ã  150 cm", "150 Ã  160 cm", "160 Ã  170 cm", 
                           "170 Ã  180 cm", "180 Ã  190 cm", "20 Ã  30 cm", "30 Ã  40 cm", 
                           "40 Ã  50 cm", "50 Ã  60 cm", "60 Ã  70 cm", "70 Ã  80 cm", "80 Ã  90 cm", 
                           "90 Ã  100 cm", "N/A"), class = "factor")

整理您的数据:

df <- as.character( df )  # convert factor to character
df <- data.frame( do.call('rbind', strsplit( df, "\ ") ), stringsAsFactors = FALSE )  # split string by spaces and row bind them together
df$X3 <- paste( df$X4, df$X5, sep = ' ')   # combine column 4 & 5 together and assign it to column 3
df[, c('X4', 'X5')] <- NULL  # remove column 4 and 5
df$X1 <- as.numeric( df$X1)  # convert column 1 to numeric
df                           # structure of data 
#    X1 X2    X3
# 1  20  Ã 30 cm
# 2  10  Ã 20 cm
# 3  40  Ã 50 cm
# 4  10  Ã 20 cm
# 5  10  Ã 20 cm
# 6  20  Ã 30 cm
# 7  40  Ã 50 cm
# 8  30  Ã 40 cm
# 9  40  Ã 50 cm
# 10 20  Ã 30 cm