我想使用 Perl 获取以前生成的 SPSS 语法文件并将其格式化以在 R 环境中使用。
对于那些熟悉 Perl 和正则表达式的人来说,这可能是一项非常简单的任务,但我遇到了困难。
我为这个 Perl 脚本制定的步骤如下:
- 读入 SPSS 文件
- 查找适当的 SPSS 文件(正则表达式)块以进行进一步处理和格式化
- 上面提到的进一步处理(更多正则表达式)
- 将 R 语法返回到命令行或最好是文件。
SPSS值标签语法的基本格式是:
...A bunch of nonsense I do not care about...
...
Value Labels
/gender
1 "M"
2 "F"
/purpose
1 "business"
2 "vacation"
3 "tiddlywinks"
execute .
...Resume nonsense...
我想要的 R 语法看起来像:
gender <- as.factor(gender
, levels= c(1,2)
, labels= c("M","F")
)
...
这是迄今为止我编写的 Perl 脚本。我已成功将每一行读入适当的数组。我有最终打印功能所需的一般流程,但我需要弄清楚如何仅为每个@vars 数组打印适当的@levels 和@labels 数组。
#!/usr/bin/perl
#Need to change to read from argument in command line
open(VARVAL, "append.txt");
@lines = <VARVAL>;
close(VARVAL);
#Read through each line and put into a variable, a value, or a reject
#I really only want to read in everything between "value labels" and "execute ."
#That probably requires more regex...
foreach (@lines){
if ($_ =~ /\//){ #Anything with a / is a variable, remove the / and push
$_ =~ tr/\///d;
push(@vars, $_)
} elsif ($_ =~/\d/) {
push(@vals, $_) #Anything that has a number in the line is a value
}
}
#Splitting each @vals array into levels or labels arrays
foreach (@vals){
@values = split(/\s+/, $_); #Splitting on a space, vunerable...better to split on first non digit character?
foreach (@values) {
if ($_ =~/\d/){
push(@levels, $_);
} else {
push(@labels, $_)
}
}
}
#Get rid of newline
#I should provavly do this somewhere else?
chomp(@vars);
chomp(@levels);
chomp(@labels);
#Need to tell it when to stop adding in @levels & @labels. While loop? Hash lookup?
#Need to get rid of final comma
#Need to redirect output to a file
foreach (@vars){
print $_ ." <- as.factor(" . $_ . "\n\t, levels = c(" ;
foreach (@levels){
print $_ . ",";
}
print ")\n\t, labels = c(";
foreach(@labels){
print $_ . ",";
}
print ")\n\t)\n";
}
最后,这是当前运行的脚本的示例输出:
gender <- as.factor(gender
, levels = c(1,2,1,2,3,)
, labels = c("M","F","biz","action","tiddlywinks",)
)
我需要这个只包括级别 1,2 和标签 M 和 F。
谢谢您的帮助!