R - 将数据帧转换为格式为featureName:featureValue的数据集

时间:2014-06-10 13:35:06

标签: r

事实证明我想要的格式叫做“SVM-Light”,并在这里描述http://svmlight.joachims.org/


我有一个数据框,我想将其转换为文本文件,格式如下:

output featureIndex:featureValue ... featureIndex:featureValue 

例如:

t = structure(list(feature1 = c(3.28, 6.88), feature2 = c(0.61, 1.83
), output = c("1", "-1")), .Names = c("feature1", "feature2", 
"output"), row.names = c(NA, -2L), class = "data.frame")

t
#   feature1 feature2 output
# 1     3.28     0.61      1
# 2     6.88     1.83     -1

会变成:

1 feature1:3.28 feature2:0.61
-1 feature1:6.88 feature2:1.83

到目前为止我的代码:

nvars = 2
l = array("row", nrow(t))
for(i in(1:nrow(t)))
{
    l = t$output[i]

    for(n in (1:nvars))
    {
        thisFeatureString = paste(names(t)[n], t[[names(t)[n]]][i], sep=":")
        l[i] = paste(l[i], thisFeatureString)
    }
}

但我不确定如何完成并将结果写入文本文件。 此外,代码可能效率不高。

是否有库函数可以执行此操作?例如,这种输出格式对于Vowpal Wabbit来说似乎很常见。

2 个答案:

答案 0 :(得分:1)

虽然 svm-light 数据格式似乎被广泛使用,但我找不到现成的解决方案。

这是一个有效的解决方案(至少在我的情况下):

############### CONVERT DATA TO SVM-LIGHT FORMAT ##################################
# data_frame MUST have a column 'target'
# target values are assumed to be -1 or 1
# all other columns are treated as features
###################################################################################
ConvertDataFrameTo_SVM_LIGHT_Format <- function(data_frame)
{
    l = array("row", nrow(data_frame)) # l for "lines"
    for(i in(1:nrow(data_frame)))
    {
        # we start each line with the target value
        l[i] = data_frame$target[i]

        # then append to the line each feature index (which is n) and its 
        # feature value (data_frame[[names(data_frame)[n]]][i])
        for(n in (1:nvars))
        {
            thisFeatureString = paste(n, data_frame[[names(data_frame)[n]]][i], sep=":")
            l[i] = paste(l[i], thisFeatureString)
        }
    }

    return (l)
}
###################################################################################

答案 1 :(得分:1)

如果您不介意输出中没有列名,我认为您可以使用简单的apply来执行此操作:

apply(t, 1, function(x) paste(x, collapse=" "))
#[1] "3.28 0.61 1"  "6.88 1.83 -1"

要将输出中的外观顺序调整到您的功能输出,您可以这样做:

apply(t[c(3, 1, 2)], 1, function(x) paste(x, collapse=" "))
#[1] "1 3.28 0.61"  "-1 6.88 1.83"