在大多数列具有多个值的情况下,重新变换为宽到宽(Reshape long to wide where most columns have multiple values)

我有以下数据:

IDnum   zipcode   City          County   State
10011   36006     Billingsley   Autauga  AL 
10011   36022     Deatsville    Autauga  AL
10011   36051     Marbury       Autauga  AL
10011   36051     Prattville    Autauga  AL
10011   36066     Prattville    Autauga  AL
10011   36067     Verbena       Autauga  AL
10011   36091     Selma         Autauga  AL
10011   36703     Jones         Autauga  AL
10011   36749     Plantersville Autauga  AL
10011   36758     Uriah         Autauga  AL
10011   36480     Atmore        Autauga  AL
10011   36502     Bon Secour    Autauga  AL

我有一个zipcodes列表,它们包含的城市,以及它们所在的县/州.IDnum =县和州的数值,合并。 列表是您现在看到的格式,我需要将其从长到宽/垂直到水平重新整形,其中IDnum变量成为唯一标识符,所有其他可能的值组合变为宽变量。

IDnum  zip1   city1        county1  state1  zip2   city2       county2
10011  36006  Billingsley  Autauga  AL      36022  Deatsville  Autauga

这只是数据集的示例,它包含了美国的每个zip,包含更多变量。 我已经看到了与此类似的其他问题和答案,但并不是几乎每列都有多个值的地方。

SPSS和STATA中的命令将以这种方式重塑数据,在SPSS中我可以运行Restructure / Cases to Vars命令,将我的初始数据集中的11个变量转换为大约1750,b / c一个县有超过290个拉链并且它重复大多数其他变量290+次。 这将创建许多空白,但我需要将它重新整形为一个非常长的水平文件。

我查看了reshape和reshape2,并挂断了'default to length'错误消息。 我确实得到了融合/ dcast以进行排序工作,但这会创建一个变量,它是所有值的列表,而不是为每个值创建变量。

melted_dupes <- melt(zip_code_list_dupes, id.vars= c("IDnum"))
HRZ_dupes <- dcast(melted_dupes, IDnum ~ variable, fun.aggregate = list) 

我尝试过tidyr和dplyr,但在语法上迷失了方向。 有点惊讶的是,没有命令数据类似于其他包中的内置命令,让我假设有,我只是没有想出来。

任何帮助表示赞赏。


I have data as below:

IDnum   zipcode   City          County   State
10011   36006     Billingsley   Autauga  AL 
10011   36022     Deatsville    Autauga  AL
10011   36051     Marbury       Autauga  AL
10011   36051     Prattville    Autauga  AL
10011   36066     Prattville    Autauga  AL
10011   36067     Verbena       Autauga  AL
10011   36091     Selma         Autauga  AL
10011   36703     Jones         Autauga  AL
10011   36749     Plantersville Autauga  AL
10011   36758     Uriah         Autauga  AL
10011   36480     Atmore        Autauga  AL
10011   36502     Bon Secour    Autauga  AL

I have a list of zipcodes, the cities they encompass, and counties/states they are located in. IDnum = numeric value for county and state, combined. List is in format you see now, I need to reshape it from long to wide / vertical to horizontal, where the IDnum variable becomes the unique identifier, and all other possible value combinations become wide variables.

IDnum  zip1   city1        county1  state1  zip2   city2       county2
10011  36006  Billingsley  Autauga  AL      36022  Deatsville  Autauga

This is just sample of the dataset, it encompasses every zip in the USA and includes more variables. I have seen other questions and answers similar to this one, but not where there are multiple values in almost every column.

There are commands in SPSS and STATA that will reshape data this way, in SPSS I can run a Restructure/Cases to Vars command that turns 11 variables in my initial dataset into about 1750, b/c one county has over 290 zips and it replicates most of the other variables 290+ times. This will create many blanks, but I need it to be reshaped into one very long horizontal file.

I have looked at reshape and reshape2, and am hung up on the 'default to length' error message. I did get melt/dcast to sorta work, but this creates one variable that is a list of all values, rather than creating variables for each value.

melted_dupes <- melt(zip_code_list_dupes, id.vars= c("IDnum"))
HRZ_dupes <- dcast(melted_dupes, IDnum ~ variable, fun.aggregate = list) 

I have tried tidyr and dplyr but got lost in syntax. Am a little surprised there isn't a command the data similar to built in commands in other packages, making me assume there is, and I just haven't figured it out.

Any help is appreciated.


原文:https://stackoverflow.com/questions/41982078
2021-05-04 11:05

满意答案

方法重写必须具有与其重写的父方法相同的方法签名 ,否则它不会被重写。

Java

public abstract class AbstractTest {

    public abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

正如你所看到的, ConcreteTest (它扩展了AbstractTest )必须覆盖test() 。 它们具有相同的方法名称,返回类型和方法参数。 子类可以省略从基类抛出的异常并抛出它自己的异常。 该子类还可以添加额外的(未)检查异常。

正如Peter Lawrey所提到的,java接口方法是隐式抽象方法(参见我在Java抽象接口上的问题 )。

这里至关重要的是,在这种情况下,方法可见性无法改变(因为它是一种层次可见性,即private-> protected-> public)。 虽然这是有效的:

public abstract class AbstractTest {

    protected abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

(父级拥有受保护的方法,子类可以覆盖相同的方法,并且只有2种可见性选择:受保护或公共权限)。

另外,假设你有

public class B {

}

public class D extends B {

}

public abstract class Base {

    public abstract B foo();
}

public class Derived extends Base {

    @Override
    public D foo() {
        // TODO Auto-generated method stub
        return new D();
    }

}

你会看到Derived返回一个D而不是B 这是为什么? 这是因为派生类遵循父类相同的签名 ,派生类的返回类型是父类的返回类型的子类型。

所以,我可以这样做:

Base pureBase = new Derived();
B b = pureBase.foo(); //which returns class D

if (b instanceof D) {
   //sure, it is, do some other logic
}

在C ++中,使用Covariant Return类型可以获得类似的效果

C ++

class AbstractTest {
public:
    virtual void test() = 0;
};


class ConcreteTest : AbstractTest {
public:
    void test() {
        //Implementation here...
    }
};

在C ++中,具有纯虚函数的类(以a =0结尾的虚函数)被称为Abstract类。 子类(在C ++中,类扩展由:分隔)覆盖纯虚方法(除了不包含=0 )。 它的父类具有相同的签名。

回到我们的Java示例,假设您有:

class B {

};

class D : B {

};

class Base {
public:
    virtual B* foo() = 0;
}

class Derived : Base {
public:
    D* foo() {
        return new D();
    }
}

在这里完成相同的推理(如java中所解释的)。 协变返回类型也适用于受保护和私有继承。 有关Covariant返回类型的更多信息。


Method overriding must have the same method signature of the parent method it's overriding, otherwise it's not called overriding.

Java:

public abstract class AbstractTest {

    public abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

As you can see, ConcreteTest (which extends AbstractTest) must override test(). They have the same method name, return types and no method parameters. The subclass can omit the exceptions thrown from the base class and throw its own Exception. The subclass can also add additional (un)checked exception.

As Peter Lawrey mentioned, a java interface methods are implicitly abstract method (See my SO question on Java Abstract Interface).

What is crucial here is that the method visibility cannot change in this case (as it's a hierarchical visibility, i.e. private->protected->public). This is valid though:

public abstract class AbstractTest {

    protected abstract void test() throws Exception;
}

public class ConcreteTest extends AbstractTest {

    @Override
    public void test() throws Exception {

    }
}

(The parent has a protected method and the subclass can override the same method and only has 2 choice for visibility: protected or public).

Also, Suppose you have

public class B {

}

public class D extends B {

}

public abstract class Base {

    public abstract B foo();
}

public class Derived extends Base {

    @Override
    public D foo() {
        // TODO Auto-generated method stub
        return new D();
    }

}

You will see that Derived returns a D and not a B. Why is that? That's because the derived class follows the same signature as the parent class and the return type of the derived class is a subtype of the return type of the parent class.

So, I can have this:

Base pureBase = new Derived();
B b = pureBase.foo(); //which returns class D

if (b instanceof D) {
   //sure, it is, do some other logic
}

In C++, you can get similar effect, using Covariant Return types

C++

class AbstractTest {
public:
    virtual void test() = 0;
};


class ConcreteTest : AbstractTest {
public:
    void test() {
        //Implementation here...
    }
};

In C++, a class with a pure virtual function (a virtual function that ends with a =0) is known as an Abstract class. The subclass (in C++, class extension is delimited by :) override the pure virtual method (except it doesn't contain the =0). It has the same signature has its parent class.

Going back to our Java example, suppose you have:

class B {

};

class D : B {

};

class Base {
public:
    virtual B* foo() = 0;
}

class Derived : Base {
public:
    D* foo() {
        return new D();
    }
}

The same reasoning (as explained in java) is done here. Covariant return types also works with protected and private inheritance. More on Covariant return types.

相关问答

更多

从C ++ / Java / C#代码中调用C方法?(Call C methods from C++/Java/C# code?)

C ++,C#,Objective-C和Java都可以调用C例程。 以下是一些链接,可以让您全面了解所询问的每种语言的C调用过程。 从Java调用C 从C ++调用C语言 从C#调用C 从Objective-C调用C. C++,C#, Objective-C, and Java can all call C routines. Here are a few links that will give you an overview of the process needed to call C fr...

java final方法vs c ++非虚函数(java final methods vs c++ nonvirtual functions)

您仍然可以在继承C ++中的类时声明具有相同签名的非虚拟成员函数,因为Java显式禁止声明具有相同签名的方法,其中基类声明该方法为final。 在处理继承/多态性时,C ++中的虚拟性有助于找到正确的函数。 例: #include <iostream> class Base { public: void doIt() { std::cout << "from Base.doIt()" << std::endl; } }; class Child : pu...

在C#中使用静态类(Overiding Static Classes in C#)

不可以。您不能重写静态成员。 你的想法很好。 只需重构代码即可使用实例成员并覆盖它们。 或者更好的是,在他的特定情况下 - 将值作为构造函数参数传递。 您不是重写任何逻辑,只需要在字段中存储和返回数据。 No. You can not override static members. Your idea is good. Just Refactor the code to use instance members and override them. Or better yet, int his ...

如何在JNI中从C ++调用Java方法(How to call Java methods from C++ in JNI)

对cout和printf C ++调用不会显示在LogCat输出中。 有两种解决方案。 使用NDK提供的记录宏允许您将消息记录到LogCat。 这对于您正在编写的新代码和包装代码很有用,但是当您拥有一个充满现有调试语句的库时不太好。 我将宏定义如下: #define LOG_INFO(info) __android_log_write(ANDROID_LOG_INFO,"JNI",info) #define LOG_ERROR(error) __android_log_write(ANDROID_...

函数/方法vs Java的C / C ++暴露(C/C++ exposure of functions / methods vs Java)

首先,有一些工具(具有不同的质量和功能)可以将编译后的机器代码逆向转换回原始语言[或其他语言,就此而言]。 这样做的最大问题是像C和C ++这样的语言,结构中成员的名称没有名称,并且通常变得“平坦”,所以最初的原因是: struct user { std::string name; int age; int score; }; 会变成: struct s0 { char *f0; char *f1; int f2; int...

在Objective C中模拟抽象类和抽象方法?(Simulate abstract classes and abstract methods in Objective C? [duplicate])

不覆盖目标c中的方法没有实际的限制。 你可以像Dan Lister在他的回答中所建议的那样使用一个协议,但这只是强制执行你的符合类来实现在该协议中声明的某种行为。 目标c中的抽象类的解决方案可能是: interface MyClass { } - (id) init; - (id) init { [NSException raise:@"Invoked abstract method" format:@"Invoked abstract method"]; return nil...

在超类中调用抽象方法,并在C ++中的子类中实现它?(Invoke abstract method in super class, and implement it in subclass in C++?)

通常,您要查找的是virtual关键字。 简而言之, virtual声明了可以覆盖此方法的意图。 请注意,这样的方法仍然可以具有实现 - virtual只是使其可重写。 要声明一个“抽象方法”,你可以说声明意图请在派生类中提供一个 = 0 ,如下所示。 这些方法在C ++中称为纯虚拟 。 但是,您应该注意一些警告。 正如下面的评论所指出的那样,你是在SuperClass构造函数中调用method() 。 不幸的是,由于构造对象的顺序,这在C ++中是不可能的。 在C ++中,派生类构造函数在分配其...

为什么隐藏Java或C ++中不允许的虚函数/方法(Why isn't hiding of virtual functions/methods allowed in Java and C++?)

你猜对了,“多态”是关键词:)多态性意味着如果Y是X一个子类,那么Y实际上就是 X ,并且可以在任何地方用作X 现在,这意味着,如果X有一个方法void k() ,那么Y也必须有相同的方法(否则,你将无法将它用作X )。 但是你不能有两个具有相同签名的不同方法,因此Yk()也必须返回void (否则,它将是一个不同的方法)。 在C ++的情况下,非虚函数不是多态的:在这种情况下, Ak和Bk是两种完全不同的方法,因此没有限制。 简而言之,让我们稍微改变你的例子:假设你定义了Xk返回int ,而Yk...

使用C ++中所有同步方法的类(Class with all synchronized methods in C++)

我可以建议两种选择: 只需使用boost::recursive_mutex (或者在C ++ 11中使用std::recursive_mutex )。 (更好)始终从同步代码调用非同步私有实现: class Test { private: mutex obj; public: void fn1() { unique_lock<mutex> lock(obj); fn1Helper(); } void fn2(bool calledFro...

C ++和Java中的抽象方法和重写函数(abstract methods and overiding function in C++ and Java)

方法重写必须具有与其重写的父方法相同的方法签名 ,否则它不会被重写。 Java : public abstract class AbstractTest { public abstract void test() throws Exception; } public class ConcreteTest extends AbstractTest { @Override public void test() throws Exception { } } 正如...

相关文章

更多

java Long型的比较

各位对于下面这种情况,不是很理解,我有一个实体类,实体类中有一个Long型的属性,是这样的: pri ...

Guava Longs类-long的实用工具类

static long fromBytes(byte b1

Mod_python: The Long Story

mod_python: the long story - Grisha Trubetskoy ...

grep 零宽断言

原文链接 参考 参考二 算是正则环视的一个简单应用吧。 http://pengqi.me/201 ...

Solr4:Tomcat7与Solr之多核配置(Multiple Cores)

1. 背景 多核,官方说法,让你只用一个Solr实例,实现多配置多索引的功能,为不同的应用保留不同的 ...

-bash: /bin/mv: Argument list too long的解决方案

在linux服务器移动文件的时候,我们一般是 mv 源文件 目标目录,如 [.....]# mv .. ...

hibernate值类型集合映射-一个顾客多个地址

顾客: Customer public class Customer { private Long ...

Guava Booleans类-布尔型基本的实用工具类

static int countTrue(boolean... values)返回为true值的数目

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本